public static void InternalApplication_BeginRequest(InternalGlobal g)
        {
            // is it ROSLYN friendly? no?
            // need to compile it by 2012?


            var BeginRequestStopwatch = Stopwatch.StartNew();


            var that    = g.InternalApplication;
            var Context = that.Context;

            var Path = Context.Request.Path;

            #region WriteFile
            var CurrentFile = g.ToCurrentFile();

            if (CurrentFile != null)
            {
                // http://betterexplained.com/articles/how-to-optimize-your-site-with-http-caching/


                //// http://www.mombu.com/programming/xbase/t-outputcache-directive-vs-responsecachesetcacheability-624773.html
                g.Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
                g.Response.Cache.SetExpires(DateTime.Now.AddMinutes(15));

                //g.EndRequest +=
                //    (_s, _e) =>
                //    {
                //Console.WriteLine("cache " + CurrentFile.Name);


                //        // http://forums.asp.net/t/1123505.aspx
                //        HttpApplication application = (HttpApplication)_s;
                //        HttpContext context = application.Context;
                //g.Response.ExpiresAbsolute = DateTime.Now.AddDays(1);
                //context.Response.AddHeader("pragma", "no-cache");
                //g.Response.AddHeader("cache-control", "public");
                g.Response.AddHeader("Content-Length", "" + CurrentFile.Length);

                var ContentType = "application/octet-stream";
                var n           = CurrentFile.Name;

                // http://www.webmaster-toolkit.com/mime-types.shtml
                if (n.EndsWith(".gif"))
                {
                    ContentType = "image/gif";
                }
                else if (n.EndsWith(".htm"))
                {
                    ContentType = "text/html";
                }

                else if (n.EndsWith(".png"))
                {
                    ContentType = "image/png";
                }
                else if (n.EndsWith(".jpg"))
                {
                    ContentType = "image/jpg";
                }
                else if (n.EndsWith(".svg"))
                {
                    ContentType = "image/svg+xml";
                }

                else if (n.EndsWith(".js"))
                {
                    ContentType = "application/x-javascript";
                }

                else if (n.EndsWith(".mp3"))
                {
                    ContentType = "audio/mpeg3";
                }
                else if (n.EndsWith(".wav"))
                {
                    ContentType = "audio/wav";
                }
                else if (n.EndsWith(".mid"))
                {
                    ContentType = "audio/midi";
                }

                else if (n.EndsWith(".css"))
                {
                    ContentType = "text/css";
                }

                that.Response.ContentType = ContentType;

                // to root
                Context.Response.WriteFile("/" + CurrentFile.Name);

                that.CompleteRequest();

                //context.Response.CacheControl = "no-cache";
                //};

                // fake lag
                //if (that.Request.Path.EndsWith(".js"))
                //    System.Threading.Thread.Sleep(1000);
                return;
            }
            #endregion



            StringAction Write =
                e =>
            {
                // could we take the method pointer implicitly?
                Context.Response.Write(e);
            };

            StringAction WriteLine =
                e =>
            {
                // could we take the method pointer implicitly?
                Write(e + Environment.NewLine);
            };



            var WebMethods = g.GetWebMethods();



            // X:\jsc.svn\examples\javascript\test\TestBaseFieldSync\TestBaseFieldSync\ApplicationWebService.cs

            #region WriteInternalFields InternalFields -> AppendCookie
            Action <InternalWebMethodInfo> WriteInternalFields =
                x =>
            {
                // does 304 check also look at
                // fields?

                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201403/20140323
                // X:\jsc.svn\examples\javascript\forms\FormsDataBindingForEnabled\FormsDataBindingForEnabled\ApplicationWebService.cs

                if (x.InternalFields == null)
                {
                    return;
                }

                // typename instead?
                var c = new HttpCookie("InternalFields");
                // X:\jsc.svn\examples\javascript\Test\TestWebServiceTaskFields\TestWebServiceTaskFields\ApplicationWebService.cs

                // X:\jsc.svn\examples\javascript\test\TestNullObjectFromWebService\TestNullObjectFromWebService\ApplicationWebService.cs

                foreach (string InternalFieldName in x.InternalFields.Keys.ToArray())
                {
                    var value = x.InternalFields[InternalFieldName];

                    Console.WriteLine(new { InternalFieldName, value });

                    if (value != null)
                    {
                        // for /xml post
                        if (Context.Request.HttpMethod == "POST")
                        {
                            // GetParameterValue: { key = _0600000e_field_elapsed }

                            that.Context.Response.AddHeader(
                                ".field " + InternalFieldName,
                                value
                                );
                        }
                        else
                        {
                            // for / get
                            c[InternalFieldName] = value;
                        }
                    }
                }

                // Set-Cookie:InternalFields=field_Foo=7; path=/
                //that.Context.Response.AppendCookie(c);
                if (Context.Request.HttpMethod == "POST")
                {
                }
                else
                {
                    that.Context.Response.SetCookie(c);
                }
            };
            #endregion



            var IsComplete = false;

            #region handler = WebServiceHandler
            var handler = new WebServiceHandler
            {
                Context = that.Context,

                CompleteRequest = delegate
                {
                    IsComplete = true;
                    that.CompleteRequest();
                },

                Applications = g.GetScriptApplications(),

                // tested by
                // X:\jsc.svn\examples\javascript\synergy\webgl\EvilChopperByPer\EvilChopperByPer\ApplicationWebService.cs
                // X:\jsc.svn\examples\javascript\synergy\webgl\WebGLDoomByInt13h\WebGLDoomByInt13h\ApplicationWebService.cs
                GetFiles = g.GetFiles,


                #region Default
                Default = delegate
                {
                    that.Response.ContentType = "text/html";

                    // todo: jsc: PHP workaround required
                    var apps = g.GetScriptApplications();
                    var app  = apps[0];



                    var Host = that.Context.Request.Headers["Host"].TakeUntilIfAny(":");

                    var CacheManifest = false;
                    //var CacheManifest = true;

                    // should disable that for android webview?

                    //if (Host == that.Context.Request.UserHostAddress)
                    //    CacheManifest = false;

                    //// webdev?
                    //if ("127.0.0.1" == that.Context.Request.UserHostAddress)
                    //    CacheManifest = false;

                    // X:\jsc.svn\examples\javascript\test\TestServiceWorkerAssetCache\TestServiceWorkerAssetCache\Application.cs
                    app.WriteTo(Write, CacheManifest);

                    IsComplete = true;
                    that.CompleteRequest();
                },
                #endregion


                Diagnostics = delegate
                {
                    that.Response.ContentType = "text/html";
                    WriteDiagnostics(g, Write, WebMethods);

                    IsComplete = true;
                    that.CompleteRequest();
                },

                Redirect = delegate
                {
                    that.Response.Redirect("/#" + that.Request.Path);

                    IsComplete = true;
                    that.CompleteRequest();
                }
            };
            #endregion

            #region handler.WriteSource
            handler.WriteSource = app =>
            {
                handler.Context.Response.ContentType = "text/javascript";

                g.Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);

                // are we not part of AppCache?
                g.Response.Cache.SetExpires(DateTime.Now.AddMinutes(15));

                //Console.WriteLine("IsConstructor WriteInternalFields");

                var Constructor = new InternalWebMethodInfo
                {
                    IsConstructor = true
                };

                // Method not found: '?'.
                // Additional information: Attempt by method 'mscorlib.<02000005IEnumerable\+ConvertToString>.ConvertToString(System.Collections.Generic.IEnumerable`1<TestIEnumerableForService.foo>)'
                // to access method '<>f__AnonymousType6`1<System.__Canon>..ctor(System.__Canon)' failed.
                g.Invoke(Constructor);

                WriteInternalFields(Constructor);



                #region GetFiles
                var ff = g.GetFiles();

                // jsc packages js files? not for long:P will switch to gzip at some point!
                var app_references = app.References.Select(
                    // why wont Single work correctly?
                    // are we embedding one file multiple times?
                    item => ff.First(k => k.Name == item.AssemblyFile || k.Name == item.AssemblyFile + ".js")
                    ).ToArray();
                #endregion



                app_references.WithEachIndex(
                    (app_ref, index) =>
                {
                    // will this work an all platforms?
                    // need to test!
                    g.Response.AddHeader("X-Reference-" + index, app_ref.Name + " " + app_ref.Length);
                }
                    );


                // tested by
                // X:\jsc.svn\examples\javascript\android\com.abstractatech.adminshell\com.abstractatech.adminshell\ApplicationWebService.cs
                #region DiagnosticsMakeItSlowAndAddSalt
                if (app.DiagnosticsMakeItSlowAndAddSalt)
                {
                    Console.WriteLine("enter DiagnosticsMakeItSlowAndAddSalt");

                    handler.Context.Response.ContentType = "application/octet-stream";


                    #region composite
                    var composite =
                        new CompositeStream(
                            app_references.Select(
                                k =>
                    {
                        return(new Func <Stream>(
                                   () =>
                        {
                            Console.WriteLine("composite: " + new { k.Name });
                            return (Stream)File.OpenRead(k.Name);
                        }
                                   ));
                    }
                                )
                            );
                    #endregion


                    Console.WriteLine("encrypting... ");

                    //var x = new MemoryStream();

                    var buffer = new byte[1024 * 40];
                    //var count = composite.GetBytes(buffer).Count();

                    #region count
                    var count = 0;


                    foreach (var y in composite.GetBytes(buffer))
                    {
                        count += y;

                        Console.WriteLine(new { count });
                    }

                    #endregion

                    // encrypting... { count = 58 }

                    Console.WriteLine("encrypting by splitting bytes... " + new { count });

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

                    var bytesleft = count;

                    g.Response.AddHeader("Content-Length", "" + (count * 2));
                    g.Response.AddHeader("X-DiagnosticsMakeItSlowAndAddSalt", "ok");


                    //                    lets write DiagnosticsMakeItSlowAndAddSalt
                    //enter DiagnosticsMakeItSlowAndAddSalt
                    //encrypting...
                    //enter GetBytes
                    //exit GetBytes
                    //encrypting... { count = 2282136 }
                    //enter GetBytes

                    // ?
                    // needs to work in .net then in android!

                    var xbuffer = new byte[buffer.Length * 2];

                    foreach (var length in composite.GetBytes(buffer))
                    {
                        Console.WriteLine("before flush of " + new { length });

                        for (int i = 0; i < length; i++)
                        {
                            var item = buffer[i];

                            var lo = (byte)(item & 0xf);
                            var hi = (byte)((item & 0xf0) >> 4);


                            xbuffer[i * 2 + 0] = lo;
                            xbuffer[i * 2 + 1] = hi;

                            //h.Context.Response.OutputStream.WriteByte(lo);
                            //h.Context.Response.OutputStream.WriteByte(hi);



                            bytesleft--;
                        }

                        handler.Context.Response.OutputStream.Write(xbuffer, 0, length * 2);
                        handler.Context.Response.Flush();

                        var timetarget = 8000 - time.ElapsedMilliseconds;

                        //                 Caused by: java.lang.ArithmeticException: divide by zero
                        //at ScriptCoreLib.Ultra.WebService.InternalGlobalExtensions___c__DisplayClasse._InternalApplication_BeginRequest_b__7(InternalGlobalExtensions___c__DisplayClasse.java:235)

                        //var ms = (int)(timetarget / bytesleft);



                        Console.WriteLine("." + new
                        {
                            bytesleft
                            //, ms
                        });

                        //if (timetarget > 0)
                        //{
                        //    Thread.Sleep(ms);
                        //}
                    }



                    Console.WriteLine("will upload done " + new { time.ElapsedMilliseconds });

                    return;
                }
                #endregion


                #region GZipAssemblyFile
                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201301/20130103

                var AcceptEncoding = handler.Context.Request.Headers["Accept-Encoding"];

                if (!string.IsNullOrEmpty(AcceptEncoding))
                {
                    if (AcceptEncoding.Contains("gzip"))
                    {
                        g.Response.AddHeader("Content-Encoding", "gzip");



                        g.Response.WriteFile("/" + app.GZipAssemblyFile);
                        handler.CompleteRequest();

                        return;
                    }
                }
                #endregion

                g.Response.AddHeader("X-Comment", "gzip was disabled");

                #region the old way


                var app_size = app_references.Sum(k => k.Length);

                // Accept-Encoding:gzip,deflate,sdch

                g.Response.AddHeader("Content-Length", "" + app_size);
                //g.Response.AddHeader("X-GZipAssemblyFile", "" + app.GZipAssemblyFile);


                foreach (var item in app_references)
                {
                    // asp.net needs absolute paths
                    handler.Context.Response.WriteFile("/" + item.Name);
                }
                #endregion


                handler.CompleteRequest();
            };
            #endregion


            #region WebMethodMetadataToken
            if (Context.Request.HttpMethod == "POST")
            {
                // X:\jsc.svn\core\ScriptCoreLib\JavaScript\BCLImplementation\System\Net\WebClient.cs

                // who sets WebMethodMetadataToken ?
                // X:\jsc.svn\core\ScriptCoreLib.Ultra\ScriptCoreLib.Ultra\JavaScript\Remoting\InternalWebMethodRequest.cs
                // C:\Users\Arvo\AppData\Local\Temp\6796$ScriptCoreLib.Ultra.dll$v4.0.30319$NoDynamic\ScriptCoreLib.JavaScript.Remoting.InternalWebMethodRequest.cs

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

                // tested by
                // X:\jsc.svn\examples\javascript\Test\TestWebMethodIPAddress\TestWebMethodIPAddress\ApplicationWebService.cs
                // X:\jsc.internal.svn\compiler\jsc.meta\jsc.meta\Library\Templates\JavaScript\InternalWebMethodRequest.cs
                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201401/20140110-xml

                //var WebMethodMetadataToken = Context.Request.QueryString[InternalWebMethodInfo.QueryKey];
                var WebMethodMetadataToken = Context.Request.Form["WebMethodMetadataToken"];
                //var value_Form = that.InternalContext.Request.Form[key];

                handler.WebMethod = InternalWebMethodInfo.First(
                    WebMethods,
                    WebMethodMetadataToken
                    );
            }
            #endregion


            g.Serve(handler);

            if (IsComplete)
            {
                return;
            }


            #region POST
            if (Context.Request.HttpMethod == "POST")
            {
                // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/04-monese/2014/201401/20140101
                //Console.WriteLine("about to load params for " + new { handler.WebMethod });

                if (handler.WebMethod == null)
                {
                    // let user defined handler handle it..
                }
                else
                {
                    // is it also supposed to load the fields?
                    handler.WebMethod.LoadParameters(that.Context);

                    Console.WriteLine("enter invoke " + new { handler.WebMethod });

                    //about to load params for { WebMethod = { IsConstructor = false, MetadataToken = 06000002, Name = Insert, TypeFullName = WebCamAvatarsExperiment.ApplicationWebService, Parameters = 1 } }
                    //about to invoke { WebMethod = { IsConstructor = false, MetadataToken = 06000002, Name = Insert, TypeFullName = WebCamAvatarsExperiment.ApplicationWebService, Parameters = 1 } }
                    // when can we invoke the webmethod and not be at /xml?

                    //try
                    //{

                    // where is the code gen?
                    // X:\jsc.internal.svn\compiler\jsc.meta\jsc.meta\Commands\Rewrite\RewriteToJavaScriptDocument.WebService.cs

                    // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/04-monese/2014/201401/20140107-dev/test
                    var WebMethodStopwatch = Stopwatch.StartNew();

                    // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201404/20140405/task
                    // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201405/20140517
                    // defined by X:\jsc.internal.svn\compiler\jsc.meta\jsc.meta\Commands\Rewrite\RewriteToJavaScriptDocument.WebService.cs

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

                    // public abstract void Invoke(InternalWebMethodInfo e);
                    g.Invoke(handler.WebMethod);


                    // BeginRequestStopwatch
                    //that.Response.AddHeader("X-BeginRequestStopwatch", "" + BeginRequestStopwatch.ElapsedMilliseconds);

                    // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/04-monese/2014/201401/20140110-stats
                    that.Response.AddHeader("X-ElapsedMilliseconds", "" + WebMethodStopwatch.ElapsedMilliseconds);

                    if (handler.WebMethod.AtElapsedMilliseconds != null)
                    {
                        handler.WebMethod.AtElapsedMilliseconds(WebMethodStopwatch.ElapsedMilliseconds);
                    }

                    //that.Response.AddHeader("X-WebMethodStopwatch", "" + SQLiteConnectionStringBuilderExtensions.ElapsedMilliseconds);

                    //}
                    //catch (Exception err)
                    //{
                    //    Console.WriteLine("boom! " + new { err });
                    //}

                    //Console.WriteLine("exit invoke " + new { handler.WebMethod });

                    //if (that.Context.Request.Path == "/xml")
                    if (that.Context.Request.Path != "/jsc")
                    {
                        // the diagnostics needs more attention down the road.


                        WriteInternalFields(handler.WebMethod);

                        // no yields
                        // why is handler.WebMethod.Results null??
                        #region 204
                        if (handler.WebMethod.Results.Length == 0)
                        {
                            if (handler.WebMethod.TaskResult == null)
                            {
                                // or should we send binary zip for webworker?
                                // NoContent
                                g.Context.Response.StatusCode = 204;
                                g.Context.Response.Flush();

                                that.CompleteRequest();
                                return;
                            }
                        }
                        #endregion


                        WriteXDocument(g, Write, handler.WebMethod);
                        that.CompleteRequest();
                        return;
                    }

                    that.Response.ContentType = "text/html";
                    WriteDiagnosticsResults(Write, handler.WebMethod);
                    WriteDiagnostics(g, Write, WebMethods);
                    that.CompleteRequest();
                    return;
                }
            }
            #endregion


            if (IsComplete)
            {
                return;
            }


            #region /favicon.ico
            if (Path == "/favicon.ico")
            {
                Context.Response.WriteFile("assets/ScriptCoreLib/jsc.ico");

                that.CompleteRequest();
                return;
            }
            #endregion



            #region /robots.txt
            if (Path == "/robots.txt")
            {
                Context.Response.StatusCode = 404;
                that.CompleteRequest();
                return;
            }
            #endregion

            #region /crossdomain.xml
            if (Path == "/crossdomain.xml")
            {
                // X:\jsc.svn\core\ScriptCoreLib.Ultra.Library\ScriptCoreLib.Ultra.Library\Ultra\WebService\InternalGlobalExtensions.InternalApplication_BeginRequest.cs
                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201401/20140109-webclient
                // http://www.adobe.com/devnet/adobe-media-server/articles/cross-domain-xml-for-streaming.html
                // X:\jsc.smokescreen.svn\market\appengine\xmoneseAIR\xmoneseAIR\ApplicationCanvas.cs
                Context.Response.Write(@"<?xml version='1.0'?>
<!-- http://www.osmf.org/crossdomain.xml -->
<!DOCTYPE cross-domain-policy SYSTEM 'http://www.adobe.com/xml/dtds/cross-domain-policy.dtd'>
<cross-domain-policy>
    <allow-access-from domain='*' />
    <site-control permitted-cross-domain-policies='all'/>
</cross-domain-policy>");

                that.CompleteRequest();
                return;
            }
            #endregion


            // cache manifest will not be needed
            // after ServiceWorker becomes useful
            // 20141230
            // X:\jsc.svn\examples\javascript\test\TestServiceWorkerAssetCache\TestServiceWorkerAssetCache\Application.cs
            #region WriteCacheManifest
            if (Path == "/" + WebApplicationCacheManifest.ManifestName)
            {
                // <html manifest="cache-manifest">

                //WriteCacheManifest(g, that, WriteLine);

                Context.Response.StatusCode = 404;
                that.CompleteRequest();
                return;
            }
            #endregion



            if (that.Request.Path == "/jsc")
            {
                handler.Diagnostics();
                return;
            }

            #region /view-source
            if (that.Request.Path == "/view-source")
            {
                var app = handler.Applications[0];

                // can we just invoke a ctor?
                // and have the fields returne?

                handler.WriteSource(app);

                return;
            }
            #endregion


            if (handler.IsDefaultPath)
            {
                handler.Default();
                return;
            }

            if (Context.Request.HttpMethod == "POST")
            {
                // we dont know what to do with this POST..
                Context.Response.StatusCode = 404;
                that.CompleteRequest();
                return;
            }

            // we could invoke web service handler now?
            handler.Redirect();
            //h.Diagnostics();
        }
コード例 #2
0
        public /* will not be part of web service itself */ void Handler(WebServiceHandler h)
        {
            if (h.Context.Request.Path == "/jsc")
            {
                h.Diagnostics();
                return;
            }


            var HostUri = new
            {
                Host = h.Context.Request.Headers["Host"].TakeUntilIfAny(":"),
                Port = h.Context.Request.Headers["Host"].SkipUntilIfAny(":")
            };

            var apps = new[]
            {
                new { path = "/WebGLLesson10", client =  h.Applications.FirstOrDefault(k => k.TypeName == "__WebGLLesson10Application") },
                new { path = "/WebGLSpiral", client =  h.Applications.FirstOrDefault(k => k.TypeName == "__WebGLSpiral") },
                new { path = "/ImpAdventures", client =  h.Applications.FirstOrDefault(k => k.TypeName == "__ImpAdventures") },
                new { path = "/IsometricTycoonViewWithToolbar", client =  h.Applications.FirstOrDefault(k => k.TypeName == "__IsometricTycoonViewWithToolbar") },
                new { path = "/McKrackenFirstRoom", client =  h.Applications.FirstOrDefault(k => k.TypeName == "__McKrackenFirstRoom") },
                //new { path = "/AvalonUgh", client =  h.Applications.FirstOrDefault(k => k.TypeName == "__AvalonUgh") },
                //new { path = "/JavaDosBoxQuakeBeta", client =  h.Applications.FirstOrDefault(k => k.TypeName == "__JavaDosBoxQuakeBeta") },
                //new { path = "/Boing4KTemplate", client =  h.Applications.FirstOrDefault(k => k.TypeName == "__Boing4KTemplate") },
                //new { path = "/RayCasterApplet", client =  h.Applications.FirstOrDefault(k => k.TypeName == "__RayCasterApplet") },
                //new { path = "/FlashCamera", client =  h.Applications.FirstOrDefault(k => k.TypeName == "__FlashCamera") },

                new { path = "", client = h.Applications.FirstOrDefault(k => k.TypeName =="Application") }
            };

            #region app
            var app = apps.FirstOrDefault(
              k =>
              {
                  if (k.path == h.Context.Request.Path)
                      return true;

                  if (h.Context.Request.Path == k.path + "/view-source")
                      return true;

                  if (h.Context.Request.Path.StartsWith(k.path))
                      return true;

                  // default
                  if (k.path == "")
                      return true;

                  return false;
              }
            );
            #endregion


            #region /view-source
            if (h.Context.Request.Path == app.path + "/view-source")
            {
                h.Context.Response.ContentType = "text/javascript";

                //// Accept-Encoding: gzip,deflate,sdch
                //foreach (var item in app.client.References)
                //{
                //    h.Context.Response.Write("/* " + new { item.AssemblyFile, bytes = 1 } + " */\r\n");
                //}

                //foreach (var item in app.client.References)
                //{
                //    // asp.net needs absolute paths
                //    //h.Context.Response.WriteFile("/" + item.AssemblyFile + ".js");

                //    // what if it does not exist?
                //    h.Context.Response.WriteFile(item.AssemblyFile + ".js");
                //}

                h.WriteSource(app.client);
                h.CompleteRequest();
                return;
            }
            #endregion

            if (app.client != null)
            {

                h.Context.Response.ContentType = "text/html";

                var xml = XElement.Parse(app.client.PageSource);

                xml.Add(
                     new XElement("script",
                         new XAttribute("src", app.path + "/view-source"),

                         // android otherwise closes the tag?
                         " "
                     )
                 );



                h.Context.Response.Write(xml.ToString());

                h.CompleteRequest();
            }
        }
        // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/20151102
        // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201510/20151022/httprequest

        public static void InternalApplication_BeginRequest(InternalGlobal g)
        {
            //Console.WriteLine("InternalApplication_BeginRequest " + new { Environment.StackTrace });

            // is it ROSLYN friendly? no?
            // need to compile it by 2012?
            //AppDomain.CurrentDomain.UnhandledException +=
            //    (s, e) =>
            //    {

            //    };


            var BeginRequestStopwatch = Stopwatch.StartNew();


            var that = g.InternalApplication;
            var Context = that.Context;

            var Path = Context.Request.Path;

            #region WriteFile
            var CurrentFile = g.ToCurrentFile();

            if (CurrentFile != null)
            {
                // http://betterexplained.com/articles/how-to-optimize-your-site-with-http-caching/


                //// http://www.mombu.com/programming/xbase/t-outputcache-directive-vs-responsecachesetcacheability-624773.html
                g.Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
                g.Response.Cache.SetExpires(DateTime.Now.AddMinutes(15));

                //g.EndRequest +=
                //    (_s, _e) =>
                //    {
                //Console.WriteLine("cache " + CurrentFile.Name);


                //        // http://forums.asp.net/t/1123505.aspx
                //        HttpApplication application = (HttpApplication)_s;
                //        HttpContext context = application.Context;
                //g.Response.ExpiresAbsolute = DateTime.Now.AddDays(1);
                //context.Response.AddHeader("pragma", "no-cache");
                //g.Response.AddHeader("cache-control", "public");
                g.Response.AddHeader("Content-Length", "" + CurrentFile.Length);

                var ContentType = "application/octet-stream";
                var n = CurrentFile.Name;

                // http://www.webmaster-toolkit.com/mime-types.shtml
                if (n.EndsWith(".gif")) ContentType = "image/gif";
                else if (n.EndsWith(".htm")) ContentType = "text/html";

                else if (n.EndsWith(".png")) ContentType = "image/png";
                else if (n.EndsWith(".jpg")) ContentType = "image/jpg";
                else if (n.EndsWith(".svg")) ContentType = "image/svg+xml";

                else if (n.EndsWith(".js")) ContentType = "application/x-javascript";

                else if (n.EndsWith(".mp3")) ContentType = "audio/mpeg3";
                else if (n.EndsWith(".wav")) ContentType = "audio/wav";
                else if (n.EndsWith(".mid")) ContentType = "audio/midi";

                else if (n.EndsWith(".css")) ContentType = "text/css";

                that.Response.ContentType = ContentType;

                // to root
                Context.Response.WriteFile("/" + CurrentFile.Name);

                that.CompleteRequest();

                //context.Response.CacheControl = "no-cache";
                //};

                // fake lag
                //if (that.Request.Path.EndsWith(".js"))
                //    System.Threading.Thread.Sleep(1000);
                return;
            }
            #endregion




            StringAction Write =
                e =>
                {
                    // could we take the method pointer implicitly?
                    Context.Response.Write(e);
                };

            StringAction WriteLine =
                e =>
                {
                    // could we take the method pointer implicitly?
                    Write(e + Environment.NewLine);
                };




            var WebMethods = g.GetWebMethods();



            // X:\jsc.svn\examples\javascript\test\TestBaseFieldSync\TestBaseFieldSync\ApplicationWebService.cs

            #region WriteInternalFields InternalFields -> AppendCookie
            Action<InternalWebMethodInfo> WriteInternalFields =
                x =>
                {
                    // Z:\jsc.svn\examples\javascript\ubuntu\UbuntuSSLWebApplication\UbuntuSSLWebApplication\ApplicationWebService.cs


                    // does 304 check also look at 
                    // fields?

                    // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201403/20140323
                    // X:\jsc.svn\examples\javascript\forms\FormsDataBindingForEnabled\FormsDataBindingForEnabled\ApplicationWebService.cs

                    if (x.InternalFields == null)
                        return;

                    // typename instead?
                    var c = new HttpCookie("InternalFields");
                    // X:\jsc.svn\examples\javascript\Test\TestWebServiceTaskFields\TestWebServiceTaskFields\ApplicationWebService.cs

                    // X:\jsc.svn\examples\javascript\test\TestNullObjectFromWebService\TestNullObjectFromWebService\ApplicationWebService.cs

                    foreach (string InternalFieldName in x.InternalFields.Keys.ToArray())
                    {

                        var value = x.InternalFields[InternalFieldName];

                        //Console.WriteLine("WriteInternalFields " + new { InternalFieldName, value });

                        if (value != null)
                        {
                            // for /xml post
                            if (Context.Request.HttpMethod == "POST")
                            {
                                // GetParameterValue: { key = _0600000e_field_elapsed }

                                // if we write her. where are they read?
                                // Z:\jsc.svn\examples\javascript\Test\TestFirefoxWebServiceField\ApplicationWebService.cs
                                // firefox filters out spaces?
                                that.Context.Response.AddHeader(
                                    ".field-" + InternalFieldName,
                                    value
                                );

                                // .field-field_foo:<_02000013>%0d%0a  <_04000021>Z3Vlc3Q=</_04000021>%0d%0a</_02000013>
                                // Z:\jsc.svn\examples\javascript\Test\TestAfterInvokeResponseHeaders\ApplicationWebService.cs

                                // 204 No Content ?
                            }
                            else
                            {

                                // for / get
                                c[InternalFieldName] = value;
                            }
                        }
                    }

                    // Set-Cookie:InternalFields=field_Foo=7; path=/
                    //that.Context.Response.AppendCookie(c);
                    if (Context.Request.HttpMethod == "POST")
                    {

                    }
                    else
                    {
                        that.Context.Response.SetCookie(c);
                    }


                };
            #endregion



            var IsComplete = false;

            #region handler = WebServiceHandler
            var handler = new WebServiceHandler
            {
                ClientCertificate = g.ClientCertificate,
                ClientTrace = g.ClientTrace,

                Context = that.Context,

                CompleteRequest = delegate
                {
                    IsComplete = true;
                    that.CompleteRequest();
                },

                Applications = g.GetScriptApplications(),

                // tested by
                // X:\jsc.svn\examples\javascript\synergy\webgl\EvilChopperByPer\EvilChopperByPer\ApplicationWebService.cs
                // X:\jsc.svn\examples\javascript\synergy\webgl\WebGLDoomByInt13h\WebGLDoomByInt13h\ApplicationWebService.cs
                GetFiles = g.GetFiles,


                #region Default
                Default = delegate
                {
                    that.Response.ContentType = "text/html";
                    //that.Response.AddHeader("Access-Control-Allow-Origin", "*");

                    // todo: jsc: PHP workaround required
                    var apps = g.GetScriptApplications();
                    var app = apps[0];








                    var Host = that.Context.Request.Headers["Host"].TakeUntilIfAny(":");

                    var CacheManifest = false;
                    //var CacheManifest = true;

                    // should disable that for android webview?

                    //if (Host == that.Context.Request.UserHostAddress)
                    //    CacheManifest = false;

                    //// webdev?
                    //if ("127.0.0.1" == that.Context.Request.UserHostAddress)
                    //    CacheManifest = false;

                    // X:\jsc.svn\examples\javascript\test\TestServiceWorkerAssetCache\TestServiceWorkerAssetCache\Application.cs
                    app.WriteTo(Write, CacheManifest);

                    IsComplete = true;
                    that.CompleteRequest();
                },
                #endregion


                Diagnostics = delegate
                {
                    that.Response.ContentType = "text/html";
                    WriteDiagnostics(g, Write, WebMethods);

                    IsComplete = true;
                    that.CompleteRequest();
                },

                Redirect = delegate
                {
                    that.Response.Redirect("/#" + that.Request.Path);

                    IsComplete = true;
                    that.CompleteRequest();
                }
            };
            #endregion

            #region handler.WriteSource
            handler.WriteSource = app =>
            {
                handler.Context.Response.ContentType = "text/javascript";

                g.Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);

                // are we not part of AppCache?
                g.Response.Cache.SetExpires(DateTime.Now.AddMinutes(15));

                //Console.WriteLine("IsConstructor WriteInternalFields");

                var Constructor = new InternalWebMethodInfo
                {
                    IsConstructor = true
                };

                // Method not found: '?'.
                // Additional information: Attempt by method 'mscorlib.<02000005IEnumerable\+ConvertToString>.ConvertToString(System.Collections.Generic.IEnumerable`1<TestIEnumerableForService.foo>)' 
                // to access method '<>f__AnonymousType6`1<System.__Canon>..ctor(System.__Canon)' failed.
                g.Invoke(Constructor);

                WriteInternalFields(Constructor);




                #region GetFiles
                var ff = g.GetFiles();

                // jsc packages js files? not for long:P will switch to gzip at some point!
                var app_references = app.References.Select(
                    // why wont Single work correctly?
                    // are we embedding one file multiple times?
                    item => ff.First(k => k.Name == item.AssemblyFile || k.Name == item.AssemblyFile + ".js")
                ).ToArray();
                #endregion



                app_references.WithEachIndex(
                    (app_ref, index) =>
                    {
                        // will this work an all platforms?
                        // need to test!
                        g.Response.AddHeader("X-Reference-" + index, app_ref.Name + " " + app_ref.Length);
                    }
                );


                // tested by
                // X:\jsc.svn\examples\javascript\android\com.abstractatech.adminshell\com.abstractatech.adminshell\ApplicationWebService.cs
                #region DiagnosticsMakeItSlowAndAddSalt
                if (app.DiagnosticsMakeItSlowAndAddSalt)
                {
                    Console.WriteLine("enter DiagnosticsMakeItSlowAndAddSalt");

                    handler.Context.Response.ContentType = "application/octet-stream";


                    #region composite
                    var composite =
                        new CompositeStream(
                           app_references.Select(
                            k =>
                            {
                                return new Func<Stream>(
                                    () =>
                                    {
                                        Console.WriteLine("composite: " + new { k.Name });
                                        return (Stream)File.OpenRead(k.Name);
                                    }
                                );
                            }
                        )
                    );
                    #endregion


                    Console.WriteLine("encrypting... ");

                    //var x = new MemoryStream();

                    var buffer = new byte[1024 * 40];
                    //var count = composite.GetBytes(buffer).Count();

                    #region count
                    var count = 0;


                    foreach (var y in composite.GetBytes(buffer))
                    {
                        count += y;

                        Console.WriteLine(new { count });
                    }

                    #endregion

                    // encrypting... { count = 58 }

                    Console.WriteLine("encrypting by splitting bytes... " + new { count });

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

                    var bytesleft = count;

                    g.Response.AddHeader("Content-Length", "" + (count * 2));
                    g.Response.AddHeader("X-DiagnosticsMakeItSlowAndAddSalt", "ok");


                    //                    lets write DiagnosticsMakeItSlowAndAddSalt
                    //enter DiagnosticsMakeItSlowAndAddSalt
                    //encrypting...
                    //enter GetBytes
                    //exit GetBytes
                    //encrypting... { count = 2282136 }
                    //enter GetBytes

                    // ? 
                    // needs to work in .net then in android!

                    var xbuffer = new byte[buffer.Length * 2];

                    foreach (var length in composite.GetBytes(buffer))
                    {
                        Console.WriteLine("before flush of " + new { length });

                        for (int i = 0; i < length; i++)
                        {
                            var item = buffer[i];

                            var lo = (byte)(item & 0xf);
                            var hi = (byte)((item & 0xf0) >> 4);


                            xbuffer[i * 2 + 0] = lo;
                            xbuffer[i * 2 + 1] = hi;

                            //h.Context.Response.OutputStream.WriteByte(lo);
                            //h.Context.Response.OutputStream.WriteByte(hi);



                            bytesleft--;




                        }

                        handler.Context.Response.OutputStream.Write(xbuffer, 0, length * 2);
                        handler.Context.Response.Flush();

                        var timetarget = 8000 - time.ElapsedMilliseconds;

                        //                 Caused by: java.lang.ArithmeticException: divide by zero
                        //at ScriptCoreLib.Ultra.WebService.InternalGlobalExtensions___c__DisplayClasse._InternalApplication_BeginRequest_b__7(InternalGlobalExtensions___c__DisplayClasse.java:235)

                        //var ms = (int)(timetarget / bytesleft);



                        Console.WriteLine("." + new
                        {
                            bytesleft
                            //, ms 
                        });

                        //if (timetarget > 0)
                        //{
                        //    Thread.Sleep(ms);
                        //}
                    }





                    Console.WriteLine("will upload done " + new { time.ElapsedMilliseconds });

                    return;
                }
                #endregion


                #region GZipAssemblyFile
                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201301/20130103

                var AcceptEncoding = handler.Context.Request.Headers["Accept-Encoding"];

                if (!string.IsNullOrEmpty(AcceptEncoding))
                    if (AcceptEncoding.Contains("gzip"))
                    {
                        g.Response.AddHeader("Content-Encoding", "gzip");



                        g.Response.WriteFile("/" + app.GZipAssemblyFile);
                        handler.CompleteRequest();

                        return;
                    }
                #endregion

                g.Response.AddHeader("X-Comment", "gzip was disabled");

                #region the old way


                var app_size = app_references.Sum(k => k.Length);

                // Accept-Encoding:gzip,deflate,sdch

                g.Response.AddHeader("Content-Length", "" + app_size);
                //g.Response.AddHeader("X-GZipAssemblyFile", "" + app.GZipAssemblyFile);


                foreach (var item in app_references)
                {
                    // asp.net needs absolute paths
                    handler.Context.Response.WriteFile("/" + item.Name);
                }
                #endregion


                handler.CompleteRequest();
            };
            #endregion


            #region WebMethodMetadataToken
            if (Context.Request.HttpMethod == "POST")
            {
                var cWebMethodMetadataToken = Context.Request.Form.AllKeys.Contains("WebMethodMetadataToken");

                //Console.WriteLine("POST is expected to include WebMethodMetadataToken " + new { cWebMethodMetadataToken });
                // X:\jsc.svn\core\ScriptCoreLib\JavaScript\BCLImplementation\System\Net\WebClient.cs

                // who sets WebMethodMetadataToken ?
                // X:\jsc.svn\core\ScriptCoreLib.Ultra\ScriptCoreLib.Ultra\JavaScript\Remoting\InternalWebMethodRequest.cs
                // C:\Users\Arvo\AppData\Local\Temp\6796$ScriptCoreLib.Ultra.dll$v4.0.30319$NoDynamic\ScriptCoreLib.JavaScript.Remoting.InternalWebMethodRequest.cs

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

                // tested by
                // X:\jsc.svn\examples\javascript\Test\TestWebMethodIPAddress\TestWebMethodIPAddress\ApplicationWebService.cs
                // X:\jsc.internal.svn\compiler\jsc.meta\jsc.meta\Library\Templates\JavaScript\InternalWebMethodRequest.cs
                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201401/20140110-xml

                //var WebMethodMetadataToken = Context.Request.QueryString[InternalWebMethodInfo.QueryKey];

                if (cWebMethodMetadataToken)
                {
                    var WebMethodMetadataToken = Context.Request.Form["WebMethodMetadataToken"];
                    //var value_Form = that.InternalContext.Request.Form[key];

                    // Z:\jsc.svn\examples\javascript\appengine\Test\TestUserHostAddress\ApplicationWebService.cs

                    if (WebMethodMetadataToken != null)
                        handler.WebMethod = InternalWebMethodInfo.First(
                            WebMethods,
                           WebMethodMetadataToken
                        );

                }
            }
            #endregion


            g.Serve(handler);

            if (IsComplete)
                return;


            #region POST
            if (Context.Request.HttpMethod == "POST")
            {
                // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/04-monese/2014/201401/20140101
                //Console.WriteLine("about to load params for " + new { handler.WebMethod });

                if (handler.WebMethod == null)
                {
                    // let user defined handler handle it..
                }
                else
                {
                    // is it also supposed to load the fields?
                    handler.WebMethod.LoadParameters(that.Context);

                    //Console.WriteLine("enter invoke " + new { handler.WebMethod });

                    //about to load params for { WebMethod = { IsConstructor = false, MetadataToken = 06000002, Name = Insert, TypeFullName = WebCamAvatarsExperiment.ApplicationWebService, Parameters = 1 } }
                    //about to invoke { WebMethod = { IsConstructor = false, MetadataToken = 06000002, Name = Insert, TypeFullName = WebCamAvatarsExperiment.ApplicationWebService, Parameters = 1 } }
                    // when can we invoke the webmethod and not be at /xml?

                    //try
                    //{

                    // where is the code gen?
                    // X:\jsc.internal.svn\compiler\jsc.meta\jsc.meta\Commands\Rewrite\RewriteToJavaScriptDocument.WebService.cs

                    // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/04-monese/2014/201401/20140107-dev/test
                    var WebMethodStopwatch = Stopwatch.StartNew();

                    // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201404/20140405/task
                    // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201405/20140517
                    // defined by X:\jsc.internal.svn\compiler\jsc.meta\jsc.meta\Commands\Rewrite\RewriteToJavaScriptDocument.WebService.cs

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

                    // public abstract void Invoke(InternalWebMethodInfo e);
                    g.Invoke(handler.WebMethod);


                    // BeginRequestStopwatch
                    //that.Response.AddHeader("X-BeginRequestStopwatch", "" + BeginRequestStopwatch.ElapsedMilliseconds);

                    // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/04-monese/2014/201401/20140110-stats
                    that.Response.AddHeader("X-ElapsedMilliseconds", "" + WebMethodStopwatch.ElapsedMilliseconds);
                    //that.Response.AddHeader("Access-Control-Allow-Origin", "*");

                    if (handler.WebMethod.AtElapsedMilliseconds != null)
                        handler.WebMethod.AtElapsedMilliseconds(WebMethodStopwatch.ElapsedMilliseconds);

                    //that.Response.AddHeader("X-WebMethodStopwatch", "" + SQLiteConnectionStringBuilderExtensions.ElapsedMilliseconds);

                    //}
                    //catch (Exception err)
                    //{
                    //    Console.WriteLine("boom! " + new { err });
                    //}

                    //Console.WriteLine("exit invoke " + new { handler.WebMethod });

                    //if (that.Context.Request.Path == "/xml")
                    if (that.Context.Request.Path != "/jsc")
                    {
                        // the diagnostics needs more attention down the road.


                        WriteInternalFields(handler.WebMethod);

                        // no yields
                        // why is handler.WebMethod.Results null??
                        #region 204
                        if (handler.WebMethod.Results.Length == 0)
                            if (handler.WebMethod.TaskResult == null)
                            {
                                // or should we send binary zip for webworker?
                                // NoContent
                                g.Context.Response.StatusCode = 204;
                                g.Context.Response.Flush();

                                that.CompleteRequest();
                                return;
                            }
                        #endregion


                        WriteXDocument(g, Write, handler.WebMethod);
                        that.CompleteRequest();
                        return;
                    }

                    that.Response.ContentType = "text/html";
                    WriteDiagnosticsResults(Write, handler.WebMethod);
                    WriteDiagnostics(g, Write, WebMethods);
                    that.CompleteRequest();
                    return;
                }
            }
            #endregion


            if (IsComplete)
                return;


            #region /favicon.ico
            if (Path == "/favicon.ico")
            {
                Context.Response.WriteFile("assets/ScriptCoreLib/jsc.ico");

                that.CompleteRequest();
                return;
            }
            #endregion



            #region /robots.txt
            if (Path == "/robots.txt")
            {
                Context.Response.StatusCode = 404;
                that.CompleteRequest();
                return;
            }
            #endregion

            #region /crossdomain.xml
            if (Path == "/crossdomain.xml")
            {
                // X:\jsc.svn\core\ScriptCoreLib.Ultra.Library\ScriptCoreLib.Ultra.Library\Ultra\WebService\InternalGlobalExtensions.InternalApplication_BeginRequest.cs
                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201401/20140109-webclient
                // http://www.adobe.com/devnet/adobe-media-server/articles/cross-domain-xml-for-streaming.html
                // X:\jsc.smokescreen.svn\market\appengine\xmoneseAIR\xmoneseAIR\ApplicationCanvas.cs
                Context.Response.Write(@"<?xml version='1.0'?>
<!-- http://www.osmf.org/crossdomain.xml -->
<!DOCTYPE cross-domain-policy SYSTEM 'http://www.adobe.com/xml/dtds/cross-domain-policy.dtd'>
<cross-domain-policy>
    <allow-access-from domain='*' />
    <site-control permitted-cross-domain-policies='all'/>
</cross-domain-policy>");

                that.CompleteRequest();
                return;
            }
            #endregion


            // cache manifest will not be needed
            // after ServiceWorker becomes useful
            // 20141230
            // X:\jsc.svn\examples\javascript\test\TestServiceWorkerAssetCache\TestServiceWorkerAssetCache\Application.cs
            #region WriteCacheManifest
            if (Path == "/" + WebApplicationCacheManifest.ManifestName)
            {
                // <html manifest="cache-manifest">

                //WriteCacheManifest(g, that, WriteLine);

                Context.Response.StatusCode = 404;
                that.CompleteRequest();
                return;
            }
            #endregion



            if (that.Request.Path == "/jsc")
            {
                handler.Diagnostics();
                return;
            }

            #region /view-source
            if (that.Request.Path == "/view-source")
            {


                var app = handler.Applications[0];

                // can we just invoke a ctor?
                // and have the fields returne?

                handler.WriteSource(app);

                return;
            }
            #endregion


            if (handler.IsDefaultPath)
            {
                handler.Default();
                return;
            }

            if (Context.Request.HttpMethod == "POST")
            {
                // Z:\jsc.svn\examples\javascript\test\TestMultipartRelated\Application.cs
                // Z:\jsc.svn\examples\javascript\ubuntu\UbuntuDualSSLWebApplication\UbuntuDualSSLWebApplication\ApplicationWebService.cs
                Console.WriteLine("invalid invoke? IE is that you?");

                // we dont know what to do with this POST..
                Context.Response.StatusCode = 404;
                that.CompleteRequest();
                return;
            }

            // we could invoke web service handler now?
            handler.Redirect();
            //h.Diagnostics();
        }
コード例 #4
0
        public /* will not be part of web service itself */ void Handler(WebServiceHandler h)
        {
            //            Content-Length:0
            //Content-Type:text/html
            //Date:Sat, 29 Dec 2012 12:42:05 GMT
            //Server:Google Frontend

            // http://blog.restphone.com/2011/04/app-engine-debug-project-gets.html
            //Caused by: java.lang.NoSuchMethodError: ScriptCoreLibJava.BCLImplementation.System.Web.__HttpRequest.get_Headers()LScriptCoreLib/Shared/BCLImplementation/System/Collections/Specialized/__NameValueCollection;
            //    at PromotionWebApplication1.ApplicationWebService___c__DisplayClass3._Handler_b__0(ApplicationWebService___c__DisplayClass3.java:46)
            //    ... 37 more
            // }

            if (h.Context.Request.Path == "/jsc")
            {
                h.Diagnostics();
                return;
            }

            if (h.Context.Request.Path == "/xxx")
            {
                h.Context.Response.Write("go away!");
                h.CompleteRequest();
                return;
            }

            try
            {
                Action foo = delegate
                {
                    var Referer = h.Context.Request.GetHeader("Referer");
                    if (Referer == null)
                        Referer = "any";

                    var HostUri = new
                    {
                        Host = h.Context.Request.GetHeader("Host").TakeUntilIfAny(":"),
                        Port = h.Context.Request.GetHeader("Host").SkipUntilIfAny(":")
                    };

                    var app = new { domain = "www.jsc-solutions.net", local = "127.0.0.1", referer = "", client = h.Applications.FirstOrDefault(k => k.TypeName == "Application") };

                    h.Context.Response.AddHeader("X-Trace", new { Referer, HostUri, app.domain } + "");

                    //var app = apps.FirstOrDefault(
                    //    k =>
                    //    {
                    //        //http://idea-remixer.tumblr.com/

                    //        if (k.referer == Referer)
                    //            return true;


                    //        // GAE has a different value for referer and port
                    //        var r = ("http://" + k.referer + "/");
                    //        if (r == Referer)
                    //            return true;


                    //        if (k.domain == HostUri.Host)
                    //            return true;

                    //        if (k.local == HostUri.Host)
                    //            return true;

                    //        if (h.Context.Request.Path == "/" + k.domain)
                    //            return true;

                    //        if (Referer.EndsWith("/" + k.domain))
                    //            return true;

                    //        // default
                    //        if (k.local == "127.0.0.1")
                    //            return true;

                    //        return false;
                    //    }
                    //);

                    //#region /view-source
                    //            var IsViewSource = h.Context.Request.Path == "/view-source";

                    //            var __explicit = "/" + app.domain + "/view-source";

                    //            if (h.Context.Request.Path == __explicit)
                    //                IsViewSource = true;

                    //            if (IsViewSource)
                    //            {
                    //                h.Context.Response.ContentType = "text/javascript";


                    //                // http://www.webscalingblog.com/performance/caching-http-headers-cache-control-max-age.html
                    //                // this will break if decision was based on referal. should use redirect instead?
                    //                h.Context.Response.AddHeader("Cache-Control", "max-age=2592000");


                    //                // Accept-Encoding: gzip,deflate,sdch
                    //                foreach (var item in app.client.References)
                    //                {
                    //                    h.Context.Response.WriteFile("" + item.AssemblyFile + ".js");
                    //                }

                    //                h.CompleteRequest();
                    //                return;
                    //            }
                    //            #endregion

                    //            if (h.IsDefaultPath)
                    //            {
                    //                h.Context.Response.ContentType = "text/html";

                    //                var xml = XElement.Parse(app.client.PageSource);

                    //                var src = __explicit;

                    //                if (HostUri.Host == app.domain)
                    //                    src = "/view-source";



                    //                xml.Add(
                    //                    new XElement("script",
                    //                        new XAttribute("src", src),

                    //                        // android otherwise closes the tag?
                    //                        " "
                    //                    )
                    //                );



                    //                h.Context.Response.Write(xml.ToString());

                    //                h.CompleteRequest();
                    //            }

                };


                // woraround return support inside try block
                foo();
            }
            catch (Exception ex)
            {
                h.Context.Response.Write("yikes! i did something stupid. " + new { ex.Message, ex.StackTrace });
                h.CompleteRequest();
            }
        }
コード例 #5
0
        public void Handle(WebServiceHandler h)
        {
            if (h.Context.Request.Path == "/jsc")
            {
                h.Diagnostics();
                return;
            }

            // all paths are ok
            var Other = h.Applications[0];

            h.Context.Response.ContentType = "text/html";

            var Key = h.Context.Request.Path;

            // revert ASP.NET 
            if (Key == "/default.htm")
                Key = "/";


            //         $element2->_ae7686222de9fe3bad0c1ab5daa69519_6000bb3(_54ab04ba467ed232b7f5d1fcb949e03c_6000bc9("div"))->_ae7686222de9fe3bad0c1ab5daa69519_6000bb3(_54ab04ba467ed232b7f5d1fcb949e03c_6000bc9("h1"))->_96b56dc7b8f4203e82a367dae19437d4_6000bc0($string1);
            var xml = XElement.Parse(Other.PageSource);

            //Console.WriteLine("Other.PageSource:");
            //Console.WriteLine(Other.PageSource);


            //Console.WriteLine("xml:");
            //Console.WriteLine(xml.ToString());

            xml.Element("body").Element("div").Element("h1").Value = Key;
            //xml.Element("div").Value = "Hello world";

            var Revision = "<div>Hello world, <a href='other page#foo'>other page</a></div>";

            this.EnumerateItems(Key,
                Content =>
                {


                    Revision = Content;
                    //xml.Element("div").Add(new XElement("hr"));
                    //xml.Element("div").Add(XElement.Parse(Revision));
                    //xml.Element("div").ReplaceWith(XElement.Parse(Content));
                }
            );

            //Console.WriteLine("Revision:");
            //Console.WriteLine(Revision);

            var Revision_xml = XElement.Parse(Revision);

            //Console.WriteLine("Revision_xml:");
            //Console.WriteLine(Revision_xml.ToString());

            xml.Element("body").Element("output").Add(Revision_xml);

            //xml.Element("h3").Value = h.Context.Request.UserAgent;
            //xml.Element("h3").Value = h.Context.Request.Headers["User-Agent"];

            //h.Context.Response.Write(
            //          "<script type='text/xml' class='" + Other.TypeName + "'></script>"
            //      );


            foreach (var r in Other.References)
            {
                xml.Add(
                    new XElement("script",
                        new XAttribute("src", "/" + r.AssemblyFile + ".js"),
                        " "
                    )
                );

                //h.Context.Response.Write(
                //    "<script src='" + r.AssemblyFile + ".js'></script>"
                //);
            }

            h.Context.Response.Write(xml.ToString());

            h.CompleteRequest();
        }
コード例 #6
0
        public void Handler(WebServiceHandler h)
        {
            // SSL certifactes seem way more likely useful.

            var HostUri = new
            {
                Host = h.Context.Request.Headers["Host"].TakeUntilIfAny(":"),
                Port = h.Context.Request.Headers["Host"].SkipUntilIfAny(":")
            };
#if DEBUG
            Console.WriteLine(h.Context.Request.HttpMethod + " " + h.Context.Request.Path);

            h.Context.Request.Headers.AllKeys.WithEach(
                k => Console.WriteLine(k + ": " + h.Context.Request.Headers[k])
            );
#endif

            // http://tools.ietf.org/html/rfc2617#section-3.2.1

            var Authorization = h.Context.Request.Headers["Authorization"];

            var AuthorizationLiteralEncoded = Authorization.SkipUntilOrEmpty("Basic ");
            var AuthorizationLiteral = Encoding.ASCII.GetString(
                Convert.FromBase64String(AuthorizationLiteralEncoded)
            );

            var AuthorizationLiteralCredentials = new
            {
                user = AuthorizationLiteral.TakeUntilOrEmpty(":"),
                password = AuthorizationLiteral.SkipUntilOrEmpty(":"),
            };

            Console.WriteLine(new { AuthorizationLiteralCredentials }.ToString());

            Action AlternativeCredentials =
                delegate
                {
                    h.Context.Response.Write(
                  new XElement("body",
                      new XElement("pre",
                          new { AuthorizationLiteralCredentials }
                      ),

                              new XElement("hr"),
                      new XElement("a", new XAttribute("href",
                          "/login"),
                          "/login"
                      ),

                           new XElement("hr"),
                      new XElement("a", new XAttribute("href",
                          "/secure"),
                          "/secure"
                      ),
                      new XElement("a", new XAttribute("href",
                          "/secure-foo"),
                          "/secure-foo"
                      ),
                      new XElement("hr"),
                      new XElement("a", new XAttribute("href",
                          "//xoo:zar@" + HostUri.Host + ":" + HostUri.Port + "/secure"),
                          "//xoo:zar@" + HostUri.Host + ":" + HostUri.Port + "/secure"
                      ),
                        new XElement("hr"),
                          new XElement("a", new XAttribute("href",
                              "//yoo:yar@" + HostUri.Host + ":" + HostUri.Port + "/secure"),
                              "//yoo:yar@" + HostUri.Host + ":" + HostUri.Port + "/secure"
                          ),
                        new XElement("hr"),
                          new XElement("a", new XAttribute("href",
                              "//zoo:@" + HostUri.Host + ":" + HostUri.Port + "/secure"),
                              "//zoo:@" + HostUri.Host + ":" + HostUri.Port + "/secure"
                          ),
                          new XElement("hr"),
                          new XElement("a", new XAttribute("href",
                              "/logout"),
                              "/logout"
                          )
                      )
              );
                };

            if (h.IsDefaultPath)
            {
                AlternativeCredentials();
                h.CompleteRequest();
                return;
            }

            if (h.Context.Request.Path == "/login")
            {
                h.Context.Response.AddHeader("Refresh", "1;url=/secure");
                h.Context.Response.Write(
                   new XElement("body",
                       new XElement("h1", "Hey!")
                     )
                );

                h.CompleteRequest();

                return;
            }

            if (h.Context.Request.Path == "/logout")
            {
                h.Context.Response.AddHeader("Refresh", "1;url=//logout:@" + HostUri.Host + ":" + HostUri.Port + "/godspeed");
                h.Context.Response.Write(
                   new XElement("body",
                       new XElement("h1", "Bye!")
                     )
                );

                h.CompleteRequest();

                return;
            }

            if (h.Context.Request.Path == "/godspeed")
            {
                h.Context.Response.AddHeader("Refresh", "4;url=/");
                AlternativeCredentials();
                h.Context.Response.Write(
                   new XElement("body",
                       new XElement("h1", "Godspeed!")
                     )
                );

                h.CompleteRequest();

                return;
            }


            if (h.Context.Request.Path == "/jsc")
            {
                h.Diagnostics();
                h.CompleteRequest();

                return;
            }





            if (!string.IsNullOrEmpty(AuthorizationLiteralCredentials.user))
                if (!string.IsNullOrEmpty(AuthorizationLiteralCredentials.password))
                {
                    var xml = XElement.Parse(global::AuthenticationExperiment.HTML.Pages.DefaultPageSource.Text);

#if DEBUG
                    // linq for andoid? when can we have it?

                    xml.Descendants("data-user").ReplaceContentWith(AuthorizationLiteralCredentials.user);
                    xml.Descendants("data-password").ReplaceContentWith(AuthorizationLiteralCredentials.password);
#endif
                    // what are the defalts on different platforms?
                    h.Context.Response.ContentType = "text/html";

                    h.Context.Response.Write(xml.ToString());


                    AlternativeCredentials();


                    h.CompleteRequest();
                    return;
                }

            h.Context.Response.StatusCode = 401;
            h.Context.Response.AddHeader(
                "WWW-Authenticate",
                "Basic realm=\"[email protected]\""
            );

            h.Context.Response.AddHeader("Refresh", "4;url=/");

            //AlternativeCredentials();
            // android flush headers?
            //h.Context.Response.Write("");
            h.Context.Response.Write(
              new XElement("body",
                  new XElement("h1", "Have we met?"),
                  new XElement("hr"),
                  new XElement("a", new XAttribute("href", "/login"), "/login")


              )
           );

            //h.Context.Response.Write("http://en.wikipedia.org/wiki/Basic_access_authentication");
            h.CompleteRequest();
        }
コード例 #7
0
        // FakeLogin
        public /* will not be part of web service itself */ void Handler(WebServiceHandler h)
        {
            if (h.Context.Request.Path == "/jsc")
            {
                h.Diagnostics();
                h.CompleteRequest();

                return;
            }

            var apps_Application = h.Applications.FirstOrDefault(k => k.TypeName == "Application");
            var apps_FakeLogin = h.Applications.FirstOrDefault(k => k.TypeName == "FakeMultimonitorDesktop");
            var apps_FakeLoginScreen = h.Applications.FirstOrDefault(k => k.TypeName == "FakeLoginScreen");
            


            var apps = new
            {
                Application = apps_Application,
                FakeLogin = apps_FakeLogin,
                FakeLoginScreen = apps_FakeLoginScreen,
            };

            var app = apps.FakeLogin;

            if (h.Context.Request.Path == "/" + apps.FakeLoginScreen.TypeName)
                app = apps.FakeLoginScreen;

            if (h.Context.Request.Path == "/" + apps.FakeLoginScreen.TypeName + "/view-source")
                app = apps.FakeLoginScreen;


            if (h.Context.Request.Path == "/" + apps.Application.TypeName)
                app = apps.Application;

            if (h.Context.Request.Path == "/" + apps.Application.TypeName + "/view-source")
                app = apps.Application;


            var __explicit = "/" + app.TypeName + "/view-source";


            #region IsDefaultPath
            var IsExplicitDefaultPath = h.Context.Request.Path == "/" + app.TypeName;
            if (h.IsDefaultPath || IsExplicitDefaultPath)
            {


                {
                    var c = h.Context.Request.Cookies["FakeLoginScreen.Delay"];

                    if (c != null)
                    {

                        Console.WriteLine("FakeLoginScreen.Delay");
                        c.Expires = DateTime.Now;
                        c.Value = "";

                        h.Context.Response.SetCookie(c);

                        Thread.Sleep(1000);
                    }
                }

                {
                    var c = h.Context.Request.Cookies["FakeLoginScreen.NoContent"];

                    if (c != null)
                    {

                        Console.WriteLine("FakeLoginScreen.NoContent");
                        c.Expires = DateTime.Now;
                        c.Value = "";

                        h.Context.Response.SetCookie(c);

                        // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
                        h.Context.Response.StatusCode = 204;
                        h.CompleteRequest();
                        return;
                    }
                }

                h.Context.Response.ContentType = "text/html";

                var xml = XElement.Parse(app.PageSource);

                var src = __explicit;

                //if (HostUri.Host == app.domain)
                //    src = "/view-source";



                xml.Add(
                    new XElement("script",
                        new XAttribute("src", src),

                        // android otherwise closes the tag?
                        " "
                    )
                );

                //h.Context.Response.Write("<!-- " + new { Referer, HostUri, app.domain } + " -->\r\n");


                h.Context.Response.Write(xml.ToString());

                h.CompleteRequest();
                return;
            }
            #endregion


            #region /view-source
            var IsViewSource = h.Context.Request.Path == "/view-source";


            if (h.Context.Request.Path == __explicit)
                IsViewSource = true;

            if (IsViewSource)
            {
                h.Context.Response.ContentType = "text/javascript";


                // http://www.webscalingblog.com/performance/caching-http-headers-cache-control-max-age.html
                // this will break if decision was based on referal. should use redirect instead?
                h.Context.Response.AddHeader("Cache-Control", "max-age=2592000");


                // Accept-Encoding: gzip,deflate,sdch
                foreach (var item in app.References)
                {
                    h.Context.Response.Write("/* " + new { item.AssemblyFile, bytes = 1 } + " */\r\n");
                }

                foreach (var item in app.References)
                {
                    // asp.net needs absolute paths
                    h.Context.Response.WriteFile("/" + item.AssemblyFile + ".js");
                }


                h.CompleteRequest();
                return;
            }
            #endregion
        }
コード例 #8
0
        public /* will not be part of web service itself */ void Handler(WebServiceHandler h)
        {
            
            var Accepts = h.Context.Request.Headers["Accept"];

            if (Accepts != null)
                if (Accepts.Contains(EventSourceGenerator.ContentType))
                {
                    // handled in the other handler?
                    return;
                }

            var path = h.Context.Request.Path;

            #region undo asp.net
            if (path == "/default.htm")
                path = "/";
            #endregion

            #region Diagnostics /jsc
            if (h.Context.Request.Path == "/jsc")
            {
                h.Diagnostics();
                h.CompleteRequest();

                return;
            }
            #endregion



            var apps = new Dictionary<string, string> 
            {
                {"", "Application"},
                {"HardwareDetection", "__HardwareDetection"},
                {"DualViewWithCamera", "__WithCamera"},

                {"__Templates", "__Templates"}
            };

            var appname = apps[""];

            var appsrc = "/view-source";
            var apppath = path.SkipUntilIfAny("/").TakeUntilIfAny("/view-source");

            if (!string.IsNullOrEmpty(apppath))
                if (apps.ContainsKey(apppath))
                {
                    appname = apps[apppath];
                    appsrc = "/" + apppath + appsrc;
                }

            var app = h.Applications.Single(k => k.TypeName == appname);

            #region /view-source

            var IsViewSource = h.Context.Request.Path.EndsWith("/view-source");
            if (IsViewSource)
            {
                h.WriteSource(app);

                //h.Context.Response.ContentType = "text/javascript";

                //h.WriteSource(app);

                //// Accept-Encoding: gzip,deflate,sdch
                //foreach (var item in app.References)
                //{
                //    h.Context.Response.Write("/* " + new { item.AssemblyFile, bytes = 1 } + " */\r\n");
                //}

                //foreach (var item in app.References)
                //{
                //    // asp.net needs absolute paths
                //    h.Context.Response.WriteFile("/" + item.AssemblyFile + ".js");
                //}


                //h.CompleteRequest();
                return;
            }
            #endregion

            #region text/html
            h.Context.Response.ContentType = "text/html";

            var xxml = XElement.Parse(app.PageSource);


            xxml.Add(
                new XElement("script",
                    new XAttribute("src", appsrc),

                    // android otherwise closes the tag?
                    " "
                )
            );

            h.Context.Response.Write(xxml.ToString());

            h.CompleteRequest();
            #endregion

        }