public void BeginRequest(HttpApplication context)
        {
            if (_host == null)
                return;
            if (context.Request.ContentType == ContentType.RTMPT)
            {
                context.Response.Clear();
                context.Response.ContentType = ContentType.RTMPT;
                ThreadContext.Properties["ClientIP"] = HttpContext.Current.Request.UserHostAddress;
                if (Log.IsDebugEnabled)
                    Log.Debug(__Res.GetString(__Res.Rtmpt_Begin));

                try
                {
                    FluorineWebContext.Initialize();
                    if (context.Request.Headers["RTMPT-command"] != null)
                    {
                        Log.Debug(string.Format("ISAPI rewrite, original URL {0}", context.Request.Headers["RTMPT-command"]));
                    }

                    if (_host.MessageServer != null)
                        _host.MessageServer.ServiceRtmpt();
                    else
                    {
                        if (Log.IsFatalEnabled)
                            Log.Fatal(__Res.GetString(__Res.MessageServer_AccessFail));
                    }
                    if (Log.IsDebugEnabled)
                        Log.Debug(__Res.GetString(__Res.Rtmpt_End));
                    // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event
                    context.CompleteRequest();
                }
                catch (Exception ex)
                {
                    Log.Fatal(__Res.GetString(__Res.Rtmpt_Fatal), ex);
                    context.Response.Clear();
                    context.Response.ClearHeaders();
                    context.Response.Status = __Res.GetString(__Res.Rtmpt_Fatal404) + " " + ex.Message;
                    // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event
                    context.CompleteRequest();
                }
            }
        }
Exemple #2
0
        public override void Respond(HttpApplication application, GlimpseConfiguration configuration)
        {
            var response = application.Response;
            var mode = application.GetGlimpseMode();

            response.Write(
                string.Format(
                    "<html><head><title>Glimpse Config</title><script>function toggleCookie(){{var mode = document.getElementById('glimpseState'); if (mode.innerHTML==='On'){{mode.innerHTML='Off';document.cookie='glimpseState=Off; path=/;'}}else{{mode.innerHTML='On';document.cookie='glimpseState=On; path=/;'}}}}</script><head><body><h1>Glimpse Config Settings:</h1><ul><li>On = {0}</li><li>Allowed IP's = <ol>",
                    configuration.On));
            foreach (IpAddress ipAddress in configuration.IpAddresses)
            {
                response.Write(string.Format("<li>{0}</li>", ipAddress.Address));
            }
            response.Write("</ol></li><li>Allowed ContentType's = <ol>");
            foreach (ContentType contentType in configuration.ContentTypes)
            {
                response.Write(string.Format("<li>{0}</li>", contentType.Content));
            }
            response.Write(
                string.Format(
                    "</ol></li></ul><h1>Your Settings:</h1><ol><li>IP = {0}</li><li>glimpseState = <input type='checkbox' id='gChk' onclick='toggleCookie();'{2}/> <label for='gChk' id='glimpseState'>{1}</lable></li></ol>",
                    application.Request.ServerVariables["REMOTE_ADDR"], mode,
                    mode == GlimpseMode.On ? " checked" : ""));

            response.Write("<h1>Bookmarklets:</h1><p>Drag the following bookmarklets to your favorites bar for quick and easy access to Glimpse.</p><ul><li><a href=\"javascript:(function(){document.cookie='glimpseState=On; path=/; expires=Sat, 01 Jan 2050 12:00:00 GMT;'; window.location.reload();})();\">Glimpse</a> - Used to turn Glimpse on.</li><li><a href=\"javascript:(function(){document.cookie='glimpseClientName='+ prompt('Client Name?') +'; path=/; expires=Sat, 01 Jan 2050 12:00:00 GMT;'; window.location.reload();})();\">Glimpse Name</a> - Used to set the client name in Glimpse requests.</li></ul></body></html>");

            application.CompleteRequest();
        }
 private void RequestAuthentication(HttpApplication app)
 {
     ApplicationServices appServices = new ApplicationServices();
     app.Response.AppendHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", appServices.Realm));
     app.Response.StatusCode = 401;
     app.CompleteRequest();
 }
 protected static void AccessDenied(HttpApplication app)
 {
     app.Response.StatusCode = ACCESS_DENIED_STATUS_CODE;
     app.Response.StatusDescription = ACCESS_DENIED_STATUS_TEXT;
     app.Response.Write(ACCESS_DENIED_STATUS_TEXT);
     app.CompleteRequest();
 }
Exemple #5
0
        public override void Respond(HttpApplication application, GlimpseConfiguration configuration)
        {
            var response = application.Response;
            var mode = application.GetGlimpseMode();

            response.Write("<!DOCTYPE html><html><head><style>body { text-align:center; font-family:\"avante garde\", \"Century Gothic\", Serif; font-size:0.8em; line-height:1.4em; } .content { position:absolute; left:50%; margin-left:-450px; text-align:left; width:900px; } h1, h2, h3, h4 { line-height:1.2em; font-weight:normal; } h1 { font-size:4em; } h2 { font-size:2.5em; } h3 { font-size:2em; } .logo { font-family: \"TitilliumMaps\", helvetica, sans-serif; margin:100px 0 40px; position:relative; background: url(http://getglimpse.com/Content/glimpseLogo.png) -10px -15px no-repeat; padding: 0 0 0 140px; } .logo h1 { color:transparent; } .logo div { font-size:1.5em; margin: 25px 0 0 -10px; } .logo blockquote { width:350px; position:absolute; right:0; top:10px; } blockquote { font: 1.2em/1.6em \"avante garde\", \"Century Gothic\", Serif; width: 400px; background: url(http://getglimpse.com/Content/close-quote.gif) no-repeat right bottom; padding-left: 18px; text-indent: -18px; } blockquote:first-letter { background: url(http://getglimpse.com/Content/open-quote.gif) no-repeat left top; padding-left: 18px; font: italic 1.4em \"avante garde\", \"Century Gothic\", Serif; } .myButton{width:175px; line-height: 1.2em; margin:0.25em 0; text-align:center; -moz-box-shadow:inset 0 1px 0 0 #fff;-webkit-box-shadow:inset 0 1px 0 0 #fff;box-shadow:inset 0 1px 0 0 #fff;background:-webkit-gradient(linear,left top,left bottom,color-stop(0.05,#ededed),color-stop(1,#dfdfdf));background:-moz-linear-gradient(center top,#ededed 5%,#dfdfdf 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ededed',endColorstr='#dfdfdf');background-color:#ededed;-moz-border-radius:6px;-webkit-border-radius:6px;border-radius:6px;border:1px solid #dcdcdc;display:inline-block;color:#777;font-family:arial;font-size:24px;padding:10px 41px;text-decoration:none;text-shadow:1px 1px 0 #fff}.myButton:hover{background:-webkit-gradient(linear,left top,left bottom,color-stop(0.05,#dfdfdf),color-stop(1,#ededed));background:-moz-linear-gradient(center top,#dfdfdf 5%,#ededed 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#dfdfdf',endColorstr='#ededed');background-color:#dfdfdf}.myButton:active{position:relative;top:1px}</style><title>Glimpse Config</title><script>function toggleCookie(){var mode = document.getElementById('glimpseState'); if (mode.innerHTML==='On'){mode.innerHTML='Off';document.cookie='glimpseState=Off; path=/;';}else{mode.innerHTML='On';document.cookie='glimpseState=On; path=/;';}}</script><head><body><div class='content'><div class=\"logo\"><blockquote>What Firebug is for the client, Glimpse does for the server... in other words, a client side Glimpse into whats going on in your server.</blockquote><h1>Glimpse</h1><div>A client side Glimpse to your server</div></div><table width=\"100%\"><tr align=\"center\"><td width=\"50%\"><a class=\"myButton\" href=\"javascript:(function(){document.cookie='glimpseState=On; path=/; expires=Sat, 01 Jan 2050 12:00:00 GMT;'; window.location.reload();})();\">Turn Glimpse On</a></td><td><a class=\"myButton\" href=\"javascript:(function(){document.cookie='glimpseClientName='+ prompt('Client Name?') +'; path=/; expires=Sat, 01 Jan 2050 12:00:00 GMT;'; window.location.reload();})();\">Set Glimpse Session Name</a></td></tr></table><p style=\"text-align:center\">Drag the above button to your favorites bar for quick and easy access to Glimpse.</p>");
            response.Write(string.Format("<h2>Glimpse Config Settings:</h2><p>This section details the Glimpse settings in your web.config file.</p><ul><li>On = {0}</li><li>Allowed IP's = <ol>", configuration.On));

            foreach (IpAddress ipAddress in configuration.IpAddresses)
            {
                response.Write(string.Format("<li>{0}</li>", ipAddress.Address));
            }
            response.Write("</ol></li><li>Allowed ContentType's = <ol>");
            foreach (ContentType contentType in configuration.ContentTypes)
            {
                response.Write(string.Format("<li>{0}</li>", contentType.Content));
            }
            response.Write(
                string.Format(
                    "</ol></li></ul><h2>Your Settings:</h2><p>This section tells you how Glimpse sees your requests.</p><ul><li>IP = {0}</li><li>glimpseState = <label for='gChk' id='glimpseState'>{1}</label></li></ul>",
                    application.Request.ServerVariables["REMOTE_ADDR"], mode));

            response.Write("<h2>Loaded Plugins:</h2><p>This is the list of Glimpse plugins loaded for this web application. Glimpse plugins show up as individual tabs in the Glimpse client.</p><ul>");

            foreach (var plugin in Module.Plugins)
            {
                response.Write("<li>" + plugin.Value.GetType() + "</li>");
            }

            response.Write("</ul><h2>More Info:</h2><p><em>For more info see <a href='http://getGlimpse.com'/>getGlimpse.com</a> or follow <a href='http://twitter.com/#!/search/%23glimpse'/>#glimpse</a> on Twitter</em></p></body></html>");

            application.CompleteRequest();
        }
 protected static void JsonResponse(HttpApplication httpApplication, string data)
 {
     var response = httpApplication.Response;
     response.Write(data);
     response.AddHeader("Content-Type", "application/json");
     httpApplication.CompleteRequest();
 }
Exemple #7
0
        public override void Respond(HttpApplication application, GlimpseConfiguration configuration)
        {
            var response = application.Response;
            var mode = application.GetGlimpseMode();

            response.Write(
                string.Format(
                    "<html><head><title>Glimpse Config</title><script>function toggleCookie(){{var mode = document.getElementById('glimpseMode'); if (mode.innerHTML==='On'){{mode.innerHTML='Off';document.cookie='glimpseMode=Off; path=/;'}}else{{mode.innerHTML='On';document.cookie='glimpseMode=On; path=/;'}}}}</script><head><body><h1>Glimpse Config Settings:</h1><ul><li>On = {0}</li><li>Allowed IP's = <ol>",
                    configuration.On));
            foreach (IpAddress ipAddress in configuration.IpAddresses)
            {
                response.Write(string.Format("<li>{0}</li>", ipAddress.Address));
            }
            response.Write("</ol></li><li>Allowed ContentType's = <ol>");
            foreach (ContentType contentType in configuration.ContentTypes)
            {
                response.Write(string.Format("<li>{0}</li>", contentType.Content));
            }
            response.Write(
                string.Format(
                    "</ol></li></ul><h1>Your Settings:</h1><ol><li>IP = {0}</li><li>GlimpseMode = <input type='checkbox' id='gChk' onclick='toggleCookie();'{2}/> <label for='gChk' id='glimpseMode'>{1}</lable></li></ol></body></html>",
                    application.Request.ServerVariables["REMOTE_ADDR"], mode,
                    mode == GlimpseMode.On ? " checked" : ""));

            application.CompleteRequest();
        }
 /// <summary>
 /// Initializes a module and prepares it to handle requests.
 /// </summary>
 /// <param name="app">An <see cref="T:System.Web.HttpApplication" /> that provides
 /// access to the methods, properties, and events common to all application objects
 /// within an ASP.NET application</param>
 public void Init(HttpApplication app)
 {
     app.BeginRequest += (src, args) =>
     {
         lock (lockObject)
         {
             if (app.Request.RawUrl == "/Stats")
             {
                 app.Response.Write(string.Format("<div>There have been {0} requests</div>",
                     requestUrls.Count));
                 app.Response.Write("<table><tr><th>ID</th><th>URL</th></tr>");
                 for (int i = 0; i < requestUrls.Count; i++)
                 {
                     app.Response.Write(
                         string.Format("<tr><td>{0}</td><td>{1}</td></tr>",
                         i, requestUrls[i]));
                 }
                 app.Response.Write("</table>");
                 app.CompleteRequest();
             }
             else
             {
                 requestUrls.Add(app.Request.RawUrl);
             }
         }
     };
 }
        private void DoPrerender(HttpApplication context)
        {
            var httpContext = context.Context;
            var request = httpContext.Request;
            var response = httpContext.Response;
            if (ShouldShowPrerenderedPage(request))
            {
                var result = GetPrerenderedPageResponse(request);

                response.StatusCode = (int)result.StatusCode;

                // The WebHeaderCollection is horrible, so we enumerate like this!
                // We are adding the received headers from the prerender service
                for (var i = 0; i < result.Headers.Count; ++i)
                {
                    var header = result.Headers.GetKey(i);
                    var values = result.Headers.GetValues(i);

                    if (values == null) continue;

                    foreach (var value in values)
                    {
                        response.Headers.Add(header, value);
                    }
                }

                response.Write(result.ResponseBody);
                response.Flush();
                context.CompleteRequest();
            }
        }
 public void Init(HttpApplication app) {
     app.BeginRequest += (src, args) => {
         if (app.Request.RawUrl.ToLower().StartsWith("/home")) {
             app.Response.StatusCode = 500;
             app.CompleteRequest();
         }
     };
 }
 /// <summary>
 /// Performs single sign out processing of the received HttpRequest.
 /// <remarks>
 /// See interface class for details.
 /// </remarks>
 public override bool ProcessRequest(HttpApplication application)
 {
   bool logoutRequestProcessed = base.ProcessRequest(application);
   if (logoutRequestProcessed) {
     application.CompleteRequest();
   }
   return logoutRequestProcessed;
 }
 protected static void createNotAuthorizedResponse(HttpApplication context, int code, int subCode, string description, bool completeRequest = true)
 {
     HttpResponse response = context.Context.Response;
     response.StatusCode = code;            
     response.StatusDescription = description;
     if (completeRequest)
         context.CompleteRequest();
 }
Exemple #13
0
 public void CompleteRequest(HttpApplication app)
 {
     var resp = app.Response;
     resp.ContentType = "application/json; charset=utf-8";
     resp.StatusCode = this.HttpStatus;
     resp.Write(this.Json);
     resp.Flush();
     app.CompleteRequest();
 }
Exemple #14
0
        public override void Respond(HttpApplication application, GlimpseConfiguration configuration)
        {
            var response = application.Response;

            ////<style>.glimpse-open { display:none; } </style>

            response.Write("<!DOCTYPE html><html><head><title>Glimpse - Popup</title><style type='text/css'>html{color:#000;background:#FFF;} body{margin:0;padding:0;} .glimpse-holder { position:relative !important; display: block !important; } .glimpse-buttons, .glimpse-open { display:none !important; } .glimpse-panel { overflow:visible !important; }</style></head><body><script src='/Scripts/jquery-1.4.4.min.js' type='text/javascript'></script><script type='text/javascript' id='glimpseClient' src='/Glimpse/glimpseClient.js'></script>");

            application.CompleteRequest();
        }
Exemple #15
0
 public void Init(HttpApplication app)
 {
     app.BeginRequest += (sender, e) =>
     {
         if (app.Context.Request.IsLocal)
         {
             app.Response.StatusCode = 403;
             app.CompleteRequest();
         }
     };
 }
 private void ValidateUserIdentity(HttpApplication app, string authorization)
 {
     string[] login = Encoding.Default.GetString(Convert.FromBase64String(authorization.Substring(6))).Split(new char[] {
                 ':'}, 2);
     if (Membership.ValidateUser(login[0], login[1]))
         app.Context.User = new RolePrincipal(new FormsIdentity(new FormsAuthenticationTicket(login[0], false, 10)));
     else
     {
         app.Response.StatusCode = 401;
         app.Response.StatusDescription = "Access Denied";
         app.Response.Write("Access denied. Please enter a valid user name and password.");
         app.CompleteRequest();
     }
 }
 /// <summary>
 /// Performs single sign out processing of the received HttpRequest.
 /// <remarks>
 /// See interface class for details.
 /// </remarks>
 public override bool ProcessRequest(HttpApplication application)
 {
   bool logoutRequestProcessed = base.ProcessRequest(application);
   if (logoutRequestProcessed) {
     // Establish an authenticated security context for this 
     // request / response discussion with the CAS server.
     // Needed because end request event always fires.
     HttpContext context = application.Context;
     context.User =  new GenericPrincipal(new GenericIdentity("CasSsorProcessed",
       CommonUtils.CAS_SERVER_AUTH_TYPE), new string[0]);
     System.Threading.Thread.CurrentPrincipal = context.User;
     application.CompleteRequest();
   }
   return logoutRequestProcessed;
 }
Exemple #18
0
        public override void Respond(HttpApplication application, GlimpseConfiguration configuration)
        {
            var response = application.Response;

            var path = VirtualPathUtility.ToAbsolute("~/", application.Context.Request.ApplicationPath);  //TODO need to centralize logic
            var requestId = ""; //TODO need to get this id from somewhere

            response.Write("<!DOCTYPE html><html><head><title>Glimpse - Popup</title>");
            response.Write("<style type='text/css'>html{color:#000;background:#FFF;} body{margin:0;padding:0;} .glimpse-holder { position:relative !important; display: block !important; } .glimpse-popout, .glimpse-popout, .glimpse-terminate, .glimpse-open { display:none !important; } .glimpse-panel { overflow:visible !important; }</style>");
            response.Write("</head><body>");
            response.Write(string.Format(@"<script type='text/javascript' id='glimpseData' data-glimpse-requestID='{1}'>var glimpse, glimpsePath = '{0}'</script>", path, requestId));
            response.Write("<script src='/Scripts/jquery-1.4.4.min.js' type='text/javascript'></script><script type='text/javascript' id='glimpseClient' src='/Glimpse/glimpseClient.js'></script>");
            response.Write("</body></html>");

            application.CompleteRequest();
        }
Exemple #19
0
        public override void Respond(HttpApplication application, GlimpseConfiguration config)
        {
            var response = application.Response;
            var assembly = Assembly.GetExecutingAssembly();

            using (var resourceStream = assembly.GetManifestResourceStream("Glimpse.Net.glimpseClient.js"))
            {
                if (resourceStream != null)
                {
                    using (var reader = new StreamReader(resourceStream))
                    {
                        response.Write(reader.ReadToEnd());
                    }
                }
            }
            response.AddHeader("Content-Type", "application/x-javascript");
            application.CompleteRequest();
        }
Exemple #20
0
        public override void Respond(HttpApplication application, GlimpseConfiguration config)
        {
            var response = application.Response;
            var assembly = Assembly.GetExecutingAssembly();

            using (var resourceStream = assembly.GetManifestResourceStream("Glimpse.Net.glimpseSprite.png"))
            {
                if (resourceStream != null)
                {
                    var byteArray = new byte[resourceStream.Length];
                    resourceStream.Read(byteArray, 0, byteArray.Length);
                    response.OutputStream.Write(byteArray, 0, byteArray.Length);
                }
            }
            response.AddHeader("Content-Type", "image/png");
            application.CompleteRequest();

            return;
        }
Exemple #21
0
        public override void Respond(HttpApplication application, GlimpseConfiguration config)
        {
            var response = application.Response;
            var assembly = Assembly.GetExecutingAssembly();

            using (var resourceStream = assembly.GetManifestResourceStream("Glimpse.Net.glimpseSprite.png"))
            {
                if (resourceStream != null)
                {
                    using (var bitmap = new Bitmap(resourceStream))
                    {
                        bitmap.Save(response.OutputStream, ImageFormat.Png);
                    }
                }
            }
            response.AddHeader("Content-Type", "image/png");
            application.CompleteRequest();

            return;
        }
Exemple #22
0
        static bool CheckAuth(HttpApplication app, Configuration sc)
        {
            AuthorizationSection ac = sc.GetSection("system.web/authorization") as AuthorizationSection;

              if (ac != null)
              {
            if (!(bool)everyoneallowed.GetValue(ac, null))
            {
              bool ok = (bool)checkuser.Invoke(ac, new object[] { app.User, app.Request.HttpMethod });
              if (!ok)
              {
            app.Context.Response.StatusCode = 401;
            app.CompleteRequest();
            return false;
              }
            }
              }

              return true;
        }
Exemple #23
0
        public void End()
        {
            if (context == null)
            {
                return;
            }

            if (context.TimeoutPossible)
            {
                Thread.CurrentThread.Abort(FlagEnd.Value);
            }
            else
            {
                // If this is called from an async event, signal the completion
                // but don't throw.
                HttpApplication app_instance = context.ApplicationInstance;
                if (app_instance != null)
                {
                    app_instance.CompleteRequest();
                }
            }
        }
Exemple #24
0
        public static void AuthenticateRequest(HttpApplication application, string realm, Func<HttpApplication, string, string, bool> authenticate)
        {
            string username = null;
            string password = null;

            string authorization = application.Request.Headers["Authorization"] ?? "";
            if(authorization.StartsWith("Basic "))
            {
                byte[] bytes = Convert.FromBase64String(authorization.Substring(6));
                string[] usernamePassword = new ASCIIEncoding().GetString(bytes).Split(':');
                username = usernamePassword[0];
                password = usernamePassword[1];
            }

            if(!authenticate.Invoke(application, username, password))
            {
                application.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                application.Response.AppendHeader("WWW-Authenticate", String.Format("Basic Realm=\"{0}\"", realm));
                application.Response.ContentType = "text/plain";
                application.Response.Write(application.Response.StatusDescription);
                application.CompleteRequest();
            }
        }
Exemple #25
0
 private void ResponseStatus(HttpApplication app, int iResponseSubStatus, string sResponseDescription)
 {
     Logging("Set ResponseStatus: " + statusCode + "." + iResponseSubStatus);
     app.Response.StatusCode = statusCode;
     app.Response.SubStatusCode = iResponseSubStatus;
     // write to browser
     app.Response.Write("Status Code " + statusCode + "." + iResponseSubStatus + ": " + sResponseDescription);
     app.CompleteRequest();
 }
Exemple #26
0
        public void ProcessRequest(HttpApplication context)
        {
            if (_host == null)
                return;
            string page = GetPageName(context.Request.RawUrl);
            if (page.ToLower() == "jsongateway.aspx")
            {
                context.Response.Clear();
                ThreadContext.Properties["ClientIP"] = HttpContext.Current.Request.UserHostAddress;
                if (Log.IsDebugEnabled)
                    Log.Debug(__Res.GetString(__Res.Json_Begin));

                try
                {
                    FluorineWebContext.Initialize();

                    Json.Rpc.JsonRpcHandler handler = new Json.Rpc.JsonRpcHandler(context.Context);
                    handler.ProcessRequest();

                    if (Log.IsDebugEnabled)
                        Log.Debug(__Res.GetString(__Res.Json_End));

                    // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event
                    context.CompleteRequest();
                }
                catch (Exception ex)
                {
                    Log.Fatal(__Res.GetString(__Res.Json_Fatal), ex);
                    context.Response.Clear();
                    context.Response.ClearHeaders();
                    context.Response.Status = __Res.GetString(__Res.Json_Fatal404) + " " + ex.Message;
                    // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event
                    context.CompleteRequest();
                }
            }
        }
Exemple #27
0
        public void ProcessRequest(HttpApplication context)
        {
            if (_host == null)
                return;
            if (context.Request.ContentType == ContentType.XForm)
            {
                string command = context.Request.Params[Messaging.Endpoints.StreamingAmfEndpoint.CommandParameterName];
                if (!Messaging.Endpoints.StreamingAmfEndpoint.OpenCommand.Equals(command) && !Messaging.Endpoints.StreamingAmfEndpoint.CloseCommand.Equals(command))
                    return;
                if (context.Request.UrlReferrer != null && !context.Request.UrlReferrer.ToString().EndsWith(".swf"))
                    return;

                context.Response.Clear();
                ThreadContext.Properties["ClientIP"] = HttpContext.Current.Request.UserHostAddress;
                if (Log.IsDebugEnabled)
                    Log.Debug(__Res.GetString(__Res.Amf_Begin));

                try
                {
                    FluorineWebContext.Initialize();

                    if (_host.MessageServer != null)
                        _host.MessageServer.Service();
                    else
                    {
                        if (Log.IsFatalEnabled)
                            Log.Fatal(__Res.GetString(__Res.MessageServer_AccessFail));
                    }
                    if (Log.IsDebugEnabled)
                        Log.Debug(__Res.GetString(__Res.Amf_End));

                    // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event
                    context.CompleteRequest();
                }
                catch (Exception ex)
                {
                    Log.Fatal(__Res.GetString(__Res.Amf_Fatal), ex);
                    context.Response.Clear();
                    context.Response.ClearHeaders();//FluorineHttpApplicationContext modifies headers
                    context.Response.Status = __Res.GetString(__Res.Amf_Fatal404) + " " + ex.Message;
                    // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event
                    context.CompleteRequest();
                }
            }
        }
Exemple #28
0
        public void ProcessRequest(HttpApplication context)
        {
            if (_host == null)
                return;
            if (context.Request.ContentType == ContentType.AMF)
            {
                _host.CompressContent(context);
                context.Response.Clear();
                context.Response.ContentType = ContentType.AMF;
                ThreadContext.Properties["ClientIP"] = HttpContext.Current.Request.UserHostAddress;
                if (Log.IsDebugEnabled)
                    Log.Debug(__Res.GetString(__Res.Amf_Begin));
                try
                {
                    FluorineWebContext.Initialize();

                    if (_host.MessageServer != null)
                        _host.MessageServer.Service();
                    else
                    {
                        if (Log.IsFatalEnabled)
                            Log.Fatal(__Res.GetString(__Res.MessageServer_AccessFail));
                    }

                    if (Log.IsDebugEnabled)
                        Log.Debug(__Res.GetString(__Res.Amf_End));

                    // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event
                    context.CompleteRequest();
                }
                catch (Exception ex)
                {
                    Log.Fatal(__Res.GetString(__Res.Amf_Fatal), ex);
                    context.Response.Clear();
                    context.Response.ClearHeaders();//FluorineHttpApplicationContext modifies headers
                    context.Response.Status = __Res.GetString(__Res.Amf_Fatal404) + " " + ex.Message;
                    // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event
                    context.CompleteRequest();
                }
            }
        }
Exemple #29
0
        private static void WriteCacheManifest(InternalGlobal g, System.Web.HttpApplication that, StringAction WriteLine)
        {
            // should the app be able to control manifest on its own?

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2013/201303/20130330-cache-manifest
            // http://html5doctor.com/go-offline-with-application-cache/
            that.Response.ContentType = WebApplicationCacheManifest.ManifestContentType;
            that.Response.AddHeader("Cache-Control", "no-cache, private");
            that.Response.AddHeader("Expires", "0");
            // http://stackoverflow.com/questions/1715568/how-to-properly-invalidate-an-html5-cache-manifest-for-online-offline-web-apps
            // Cache-Control: no-cache, private

            #region w
            var w = new StringBuilder();

            // http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html

            w.AppendLine("CACHE MANIFEST");

            var files = g.GetFiles();
            var bytes = 0;

            // do we need these?
            //w.AppendLine(WebApplicationIcon.Icon);
            //w.AppendLine(WebApplicationIcon.Image);

            //Explicit entries

            w.AppendLine("/");
            w.AppendLine("/view-source");


            foreach (var item in files)
            {
                var Command = item.Name;

                bytes += item.Length;

                // webkit seems to have 5MB limit.
                // http://groups.google.com/a/chromium.org/group/chromium-html5/browse_thread/thread/e911f18b905d28ee/9f54c8cc1e8afb5d
                // http://stackoverflow.com/questions/2908459/mobile-safari-5mb-html5-application-cache-limit
                // http://www.yuiblog.com/blog/2010/07/12/mobile-browser-cache-limits-revisited/

                // hack.

                // we need to figure out how to make the application fit to the cache limits.
                // we could be optimizing javascript.

                if (Command.EndsWith(".css"))
                {
                    w.AppendLine(Command);
                }

                if (Command.EndsWith(".swf"))
                {
                    w.AppendLine(Command);
                }

                // There’s no technical benefit to WOFF over TTF.
                if (Command.EndsWith(".ttf"))
                {
                    w.AppendLine(Command);
                }
            }

            w.AppendLine("");


            // what about fake pages used by historic api?
            // X:\jsc.svn\examples\javascript\async\AsyncHistoricActivities\AsyncHistoricActivities\Application.cs
            //w.AppendLine("FALLBACK:");
            //w.AppendLine("/fake-right /#/fake-right");

            // Application Cache Error event: Resource fetch failed (-1) http://192.168.43.252:30821/fake-right
            // http://alistapart.com/article/application-cache-is-a-douchebag


            w.AppendLine("SETTINGS:");
            w.AppendLine("prefer-online");

            // http://html5doctor.com/go-offline-with-application-cache/
            // The first value is the request URI to match, and the second is the resource sent upon matching. It caches the resource on the right for offline use, so this should be an explicit path.
            //w.AppendLine("FALLBACK:");
            //w.AppendLine("/ /#offline");



            w.AppendLine("");
            w.AppendLine("NETWORK:");
            w.AppendLine("*");

            var now = DateTime.Now;

            // Application Cache Error event: Manifest changed during update, scheduling retry
            w.AppendLine("");
            w.AppendLine("# " + new { bytes });
            w.AppendLine("");
            #endregion

            //            Implementation not found for type import :
            //type: System.Text.StringBuilder
            //method: Int32 get_Length()
            //Did you forget to add the [Script] attribute?
            //Please double check the signature!


            that.Response.AddHeader("Content-Length", "" + w.Length);
            // chrome://appcache-internals/
            that.Response.Write(w.ToString());


            that.CompleteRequest();
        }
        private void ProcessRequest(HttpApplication app, HttpRequest request)
        {
            DirectResponse responseObject = new DirectResponse(true);

            try
            {
                HttpContext context = HttpContext.Current;
                
                // Get handler
                HandlerMethods handler = HandlerMethods.GetHandlerMethods(context, request.FilePath);

                if (handler == null)
                {
                    throw new Exception("The Method '{0}' has not been defined.".FormatWith(request.FilePath));
                }

                // Get method name to invoke
                string methodName = HandlerMethods.GetMethodName(context);

                if (methodName.IsEmpty())
                {
                    throw new Exception("No methodName has been set in the configuration.");
                }


                DirectMethod directMethod = handler.GetStaticMethod(methodName);

                if (directMethod == null)
                {
                    throw new Exception("The static DirectMethod '{0}' has not been defined.".FormatWith(directMethod));
                }

                object result = directMethod.Invoke();

                if (!ResourceManager.AjaxSuccess)
                {
                    responseObject.Success = false;
                    responseObject.ErrorMessage = ResourceManager.AjaxErrorMessage;
                }
                else
                {
                    responseObject.Result = result;
                    responseObject.Script = ResourceManager.GetInstanceScript();
                }
            }
            catch (Exception e)
            {
                if (HandlerMethods.RethrowException(HttpContext.Current))
                {
                    throw e;
                }

                responseObject.Success = false;
                responseObject.ErrorMessage = IsDebugging ? e.ToString() : e.Message;
            }

            app.Context.Response.Clear();
            app.Context.Response.ClearContent();
            app.Context.Response.ClearHeaders();
            app.Context.Response.StatusCode = 200;
            app.Context.Response.ContentType = "application/json";
            app.Context.Response.Charset = "utf-8";
            app.Context.Response.Cache.SetNoServerCaching();
            app.Context.Response.Cache.SetMaxAge(TimeSpan.Zero);
            app.Context.Response.Write(responseObject.ToString());
            app.CompleteRequest();
        }
 /// <summary>
 /// Responds with 401 - Access Denied to the client
 /// </summary>
 protected void AccessDenied(HttpApplication context, String username)
 {
     HttpResponse response = context.Response;
     response.StatusCode = (int)HttpStatusCode.Unauthorized;
     response.StatusDescription = "Unauthorized";
     response.ContentType = "text/html";
     response.Write("Unauthorized");
     context.CompleteRequest();
 }
        public HostedHttpRequestAsyncResult(HttpApplication context, string aspNetRouteServiceVirtualPath, bool flowContext, bool ensureWFService, AsyncCallback callback, object state) :
            base(callback, state)
        {
            if (context == null)
            {
                throw FxTrace.Exception.ArgumentNull("context");
            }

            AspNetPartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();

            HostedAspNetEnvironment.TrySetWebSocketVersion(context);
            this.context = context;
            // WebSockets require the integrated pipeline mode and the WebSocket IIS module to be loaded. If these conditions 
            // are not met, the HttpContext.IsWebSocketRequest property throws. Also, if these conditions are not met,
            // we do not let WebSocket listeners to be started (we fail the service activation), so setting the 'isWebSocketRequest' flag 
            // to false in this case will not create confusion (or make troubleshooting difficult).
            this.isWebSocketRequest = HttpRuntime.UsingIntegratedPipeline && AspNetEnvironment.Current.IsWebSocketModuleLoaded && this.context.Context.IsWebSocketRequest;
            this.flowContext = flowContext;
            if (ensureWFService)
            {
                // check for CBA scenario. if true, service should be handled by WCF instead of WF, 
                // set this.ensureWFservice to false
                if (ServiceHostingEnvironment.IsConfigurationBasedService(context, out this.configurationBasedServiceVirtualPath))
                {
                    this.ensureWFService = false;
                }
                else
                {
                    this.ensureWFService = true;
                }
            }

            if (!string.IsNullOrEmpty(aspNetRouteServiceVirtualPath))
            {
                // aspnet routing can hijack CBA request as we append {*pathInfo} to urlpattern and there is no real file for CBA 
                // check for CBA scenario. if the request is hijacked. i.e., 
                // 1) route maps to a virtual directory:
                // aspNetRouteServiceVirtualPath <> context.Request.AppRelativeCurrentExecutionFilePath == configurationBasedServiceVirtualPath 
                // if RouteExistingFiles <> true, set aspnetRouteServiceVirtualPath to null so that the request will be treated as CBA
                // if RouteExistingFiles == true, this hijack is by-design, do nothing
                // 2) route maps to a CBA entry:
                // aspNetRouteServiceVirtualPath == context.Request.AppRelativeCurrentExecutionFilePath == configurationBasedServiceVirtualPath
                // we will use RouteExistingFiles to decide which service should be activated. We do it in ServiceHostingEnviroment.HostingManager, 
                // as we cannot pass this info to the latter. 
                if (!RouteTable.Routes.RouteExistingFiles &&
                    ServiceHostingEnvironment.IsConfigurationBasedService(context, out this.configurationBasedServiceVirtualPath))
                {
                    this.AspNetRouteServiceVirtualPath = null;
                }
                else
                {
                    this.AspNetRouteServiceVirtualPath = aspNetRouteServiceVirtualPath;
                }
            }

            // If this is a DEBUG request, complete right away and let ASP.NET handle it.
            string method = context.Request.HttpMethod ?? "";
            char firstMethodChar = method.Length == 5 ? method[0] : '\0';
            if ((firstMethodChar == 'd' || firstMethodChar == 'D') &&
                string.Compare(method, "DEBUG", StringComparison.OrdinalIgnoreCase) == 0)
            {
                if (DiagnosticUtility.ShouldTraceVerbose)
                {
                    TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.WebHostDebugRequest, SR.TraceCodeWebHostDebugRequest, this);
                }

                this.state = State.Completed;
                Complete(true, null);
                return;
            }

            this.impersonationContext = new HostedImpersonationContext();

            if (flowContext)
            {
                if (ServiceHostingEnvironment.AspNetCompatibilityEnabled)
                {
                    // Capture HttpContext/culture context if necessary.  Can be used later by HostedHttpInput to re-apply
                    // the culture during dispatch.  Also flowed here.
                    hostedThreadData = new HostedThreadData();
                }
            }

            // Set this up before calling IncrementRequestCount so if it fails, we don't leak a count.
            Action<object> iotsCallback = (AspNetPartialTrustHelpers.NeedPartialTrustInvoke || flowContext) ?
                WaitOnBeginRequestWithFlow : WaitOnBeginRequest;

            // Tell ASPNET to by-pass all the other events so no other http modules will
            // be invoked, Indigo basically takes over the request completely. This should
            // only be called in non-AspNetCompatibilityEnabled mode.
            if (!ServiceHostingEnvironment.AspNetCompatibilityEnabled && !this.ensureWFService)
            {
                context.CompleteRequest();
            }

            // Prevent ASP.NET from generating thread aborts in relation to this request.
            context.Server.ScriptTimeout = int.MaxValue;

            ServiceHostingEnvironment.IncrementRequestCount(ref this.eventTraceActivity, context.Request.AppRelativeCurrentExecutionFilePath);

            IOThreadScheduler.ScheduleCallbackLowPriNoFlow(iotsCallback, this);
        }