public void Init(System.Web.HttpApplication context)
 {
     context.BeginRequest += Application_BeginRequest;
     context.EndRequest   += Application_EndRequest;
     RootURL = System.Configuration.ConfigurationManager.AppSettings["ROOT_URL"];
     if (string.IsNullOrEmpty(RootURL))
     {
         RootURL = "http://localhost";
     }
     MenCacheHost = System.Configuration.ConfigurationManager.AppSettings["MEMCACHE_HOST"];
     if (string.IsNullOrEmpty(MenCacheHost))
     {
         MenCacheHost = "127.0.0.1:11211";
     }
     Boolean.TryParse(System.Configuration.ConfigurationManager.AppSettings["ENABLED_MEMCACHE"], out MenCacheEnabled);
     Boolean.TryParse(System.Configuration.ConfigurationManager.AppSettings["ENABLED_WEBCACHE"], out WebCacheEnabled);
     GetDespatch = new Despatch();
     try
     {
         if (MenCacheEnabled)
         {
             MenCache = new CacheManager(MenCacheHost);
         }
     }
     catch
     {
     }
 }
 ///<summary>Implements IHttpModule.Init.  Hooks to Application_OnBeginRequest.</summary>
 public void Init(System.Web.HttpApplication Application)
 {
     if (ForceSecure != RequireHttps.None || RequireCertificate != RequireHttps.None)
     {
         Application.BeginRequest += new EventHandler(OnBeginRequest);
     }
 }
        public static IISCompressionModule Register(System.Web.HttpApplication application)
        {
            IISCompressionModule module = new IISCompressionModule();

            module.Init(application);
            return(module);
        }
示例#4
0
        /// <summary>
        /// Initializes the module and prepares it to handle requests.
        /// </summary>
        
        protected override void OnInit(HttpApplication application)
        {
            if (application == null)
                throw new ArgumentNullException("application");

            //
            // Get the configuration section of this module.
            // If it's not there then there is nothing to initialize or do.
            // In this case, the module is as good as mute.
            //

            var config = (IDictionary) GetConfig();

            if (config == null)
                return;

            var userName = GetSetting(config, "userName", string.Empty);
            var password = GetSetting(config, "password", string.Empty);
            var statusFormat = GetSetting(config, "statusFormat", "{Message}");
            var maxStatusLength = int.Parse(GetSetting(config, "maxStatusLength", "140"), NumberStyles.None, CultureInfo.InvariantCulture);
            var ellipsis = GetSetting(config, "ellipsis", /* ... */ "\x2026");
            var formFormat = GetSetting(config, "formFormat", "status={0}");
            var url = new Uri(GetSetting(config, "url", "http://twitter.com/statuses/update.xml"), UriKind.Absolute);

            _credentials = new NetworkCredential(userName, password);
            _statusFormat = statusFormat;
            _url = url;
            _maxStatusLength = maxStatusLength;
            _ellipsis = ellipsis;
            _formFormat = formFormat;
            _requests = new List<WebRequest>(); // TODO Synchronization

            application.Error += OnError;
            ErrorSignal.Get(application).Raised += OnErrorSignaled;
        }
 /// <summary>
 /// Performs initializations / startup functionality when an instance of this HttpModule
 /// is being created.
 /// </summary>
 /// <param name="context">the current HttpApplication</param>        
 public void Init(HttpApplication context)
 {
     // Register our event handlers.  These are fired on every HttpRequest.
     context.BeginRequest += OnBeginRequest;
     context.AuthenticateRequest += OnAuthenticateRequest;
     context.EndRequest += OnEndRequest;
 }
 internal PageAsyncTaskManager(Page page)
 {
     this._page = page;
     this._app = page.Context.ApplicationInstance;
     this._tasks = new ArrayList();
     this._resumeTasksCallback = new WaitCallback(this.ResumeTasksThreadpoolThread);
 }
示例#7
0
 public void Init(HttpApplication context)
 {
     // 下面是如何处理 LogRequest 事件并为其
     // 提供自定义日志记录实现的示例
     context.LogRequest += new EventHandler(OnLogRequest);
     context.AcquireRequestState += new EventHandler(context_AcquireRequestState);
 }
        public void Init(System.Web.HttpApplication context)
        {
            rewriteOnlyVirtualUrls = UrlRewriting.Configuration.RewriteOnlyVirtualUrls;
            _contextItemsPrefix    = UrlRewriting.Configuration.ContextItemsPrefix;

            // Copy Settings for easier and faster Accesss during requests
            foreach (RewriteSettings rewriteSettings in UrlRewriting.Configuration.Rewrites)
            {
                RewriteRule rewrite      = null;
                string      providerName = rewriteSettings.Provider;
                if (string.IsNullOrEmpty(providerName))
                {
                    rewrite = UrlRewriting.CreateRewriteRule();
                }
                else
                {
                    rewrite = UrlRewriting.CreateRewriteRule(providerName);
                }
                rewrite.Initialize(rewriteSettings);
                AddRewriteRuleInternal(rewrite);
            }
            context.BeginRequest              += new EventHandler(OnBeginRequest);
            context.PreRequestHandlerExecute  += new EventHandler(OnAppPreRequestHandlerExecute);
            context.PostRequestHandlerExecute += new EventHandler(OnAppPostRequestHandlerExecute);
        }
        public void Init(HttpApplication context)
        {
            if (context.Application[AppVarName] == null)
                context.Application[AppVarName] = DateTime.Now;

            context.PostReleaseRequestState += ContextPostReleaseRequestState;
        }
示例#10
0
        /// <summary>��д��ַ</summary>
        /// <param name="requestedRawUrl">�����ĵ�ַ</param>
        /// <param name="app">HttpApplication ʵ��</param>
        protected override void Rewrite(string requestedPath, System.Web.HttpApplication application)
        {
            // get the configuration rules
            RewriterRuleCollection rules = RewriterConfigurationView.Instance.Configuration.Rules;

            // iterate through each rule...
            for (int i = 0; i < rules.Count; i++)
            {
                // get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)
                string lookfor = "^" + RewriterUtils.ResolveUrl(application.Context.Request.ApplicationPath, rules[i].Lookfor) + "$";

                // Create a regex (note that IgnoreCase is set...)
                Regex re = new Regex(lookfor, RegexOptions.IgnoreCase);

                // See if a match is found
                if (re.IsMatch(requestedPath))
                {
                    // match found - do any replacement needed
                    string sendToUrl = RewriterUtils.ResolveUrl(application.Context.Request.ApplicationPath, re.Replace(requestedPath, rules[i].Sendto));

                    // Rewrite the URL
                    RewriterUtils.RewriteUrl(application.Context, sendToUrl);

                    // exit the for loop
                    break;
                }
            }
        }
示例#11
0
		public AsyncHandler(AsyncCallback callback, FluorineGateway gateway, HttpApplication httpApplication, Object state) {
			_gateway = gateway;
			_callback = callback;
			_httpApplication = httpApplication;
			_state = state;
			_completed = false;
		}
 public void Init(HttpApplication context)
 {
     // Register event handlers
     context.BeginRequest += OnApplicationBeginRequest;
     context.AuthenticateRequest += OnApplicationAuthenticateRequest;
     context.EndRequest += OnApplicationEndRequest;
 }
		/// <summary>
		/// Inits the specified app.
		/// </summary>
		/// <param name="app">The app.</param>
		public void Init(HttpApplication app)
		{
			app.BeginRequest += OnBeginRequest;

			try
			{
				var httpHandlersConfig =
					(HttpHandlersSection) WebConfigurationManager.GetSection("system.web/httpHandlers");

				foreach(HttpHandlerAction handlerAction in httpHandlersConfig.Handlers)
				{
					if (typeof(MonoRailHttpHandlerFactory).IsAssignableFrom(Type.GetType(handlerAction.Type)))
					{
						if (handlerAction.Path.StartsWith("*."))
						{
							defaultUrlExtension = handlerAction.Path.Substring(1);
							break;
						}
						else if (handlerAction.Path == "*")
						{
							defaultUrlExtension = string.Empty;
						}
					}
				}
			}
			catch 
			{
				//just swallow and keep on using .castle as the default.
			}

		}
        /// <summary>
        /// Initializes a module and prepares it to handle requests.
        /// </summary>
        /// <param name="context">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 context)
        {
            var service = diagnosticsService.Value;

            context.BeginRequest += BeginRequest;
            context.EndRequest += EndRequest;
        }        
        /// <summary>
        /// Determines whether the specified context is authenticated.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>
        ///   <c>true</c> if the specified context is authenticated; otherwise, <c>false</c>.
        /// </returns>
        private bool IsAuthenticated(HttpApplication context) {
            string authHeader = context.Request.Headers["Authorization"];

            if(!string.IsNullOrEmpty(authHeader)) {

                if(authHeader.StartsWith("basic ", StringComparison.InvariantCultureIgnoreCase)) {
                    string userNameAndPassword = Encoding.Default.GetString(

                    Convert.FromBase64String(authHeader.Substring(6)));

                    string[] parts = userNameAndPassword.Split(':');

                    BasicUser bu = new BasicUser();
                    bu.UserName = parts[0];
                    bu.Password = parts[1];

                    if(BasicAuthenticationHelper.Authenticate(bu.UserName, bu.Password)) {
                        CookieHelper.SetBasicAuthCookie(bu);
                        return true;
                    } else {
                        if(!string.IsNullOrEmpty(CookieHelper.GetBasicAuthCookie())) {
                            CookieHelper.RemoveBasicAuthCookie();
                        }
                        return false;
                    }
                }
            }
            return false;
        }
示例#16
0
		/// <summary>
		/// Initializes a module and prepares it to handle requests.
		/// </summary>
		/// <param name="context">An <see cref="T:System.Web.HttpApplication"></see> that provides access to the methods,
		/// properties, and events common to all application objects within an ASP.NET application </param>
		public void Init(HttpApplication context)
		{
			if (!IoC.IsInitialized)
			{
				InitializeContainer(this);
			}
		}
示例#17
0
		OutputCacheProvider FindCacheProvider (HttpApplication app)
		{				
#if NET_4_0
			HttpContext ctx = HttpContext.Current;
			if (app == null) {
				app = ctx != null ? ctx.ApplicationInstance : null;

				if (app == null)
					throw new InvalidOperationException ("Unable to find output cache provider.");
			}

			string providerName = app.GetOutputCacheProviderName (ctx);
			if (String.IsNullOrEmpty (providerName))
				throw new ProviderException ("Invalid OutputCacheProvider name. Name must not be null or an empty string.");

			OutputCacheProvider ret = OutputCache.GetProvider (providerName);
			if (ret == null)
				throw new ProviderException (String.Format ("OutputCacheProvider named '{0}' cannot be found.", providerName));

			return ret;
#else
			if (provider == null)
				provider = new InMemoryOutputCacheProvider ();
			
			return provider;
#endif
		}
示例#18
0
        private static void CleanupHttpSession(System.Web.HttpApplication context)
        {
            // Get a reference to the session module
            IHttpModule module = context.Modules["Session"];

            if (module != null && module.GetType() == typeof(SessionStateModule))
            {
                SessionStateModule stateModule = (SessionStateModule)module;
                stateModule.Start += (sender, args) =>
                {
                    // Ensure that expired NHibernate sessions are disposed
                    SessionManager.Instance.GetSession(SessionManager.Instance.DefaultSessionKey);
                    SessionEndModule.SessionObjectKey = SessionManager.SessionKeyIdentifier;
                    EventHandler <SessionEndedEventArgs> sessionEndHandler = null;

                    sessionEndHandler = (s, a) =>
                    {
                        SessionManager.Instance.DisposeSession((Guid)(a.SessionObject));
                        SessionEndModule.SessionEnd -= sessionEndHandler;
                    };

                    SessionEndModule.SessionEnd += sessionEndHandler;
                };
            }
        }
示例#19
0
 protected static void JsonResponse(HttpApplication httpApplication, string data)
 {
     var response = httpApplication.Response;
     response.Write(data);
     response.AddHeader("Content-Type", "application/json");
     httpApplication.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();
 }
示例#21
0
 /// <summary>
 /// Initializes a module and prepares it to handle requests.
 /// </summary>
 /// <param name="context">An <see cref="T:System.Web.HttpApplication"></see> 
 /// that provides access to the methods, properties, and events common to 
 /// all application objects within an ASP.NET application.
 /// </param>
 void IHttpModule.Init(HttpApplication context)
 {
     if (BlogSettings.Instance.EnableHttpCompression)
     {
         context.PreRequestHandlerExecute += new EventHandler(context_PostReleaseRequestState);
     }
 }
示例#22
0
        void WebEvents_OnLoadRequestedPath(System.Web.HttpApplication app, string sprocketPath, string[] pathSections, HandleFlag handled)
        {
            if (!IntegrationEnabled)
            {
                return;
            }

            switch (sprocketPath)
            {
            case "paypal-ipn-process":
                using (PayPalTransactionResponse resp = InstantPaymentNotification.Authenticate())
                {
                    if (OnInstantPaymentNotification != null && resp != null)
                    {
                        OnInstantPaymentNotification(resp);
                    }
                }

                break;

            case "paypal-trans-return":
                using (PayPalTransactionResponse resp = TransactionReturn())
                {
                    if (OnTransactionResponse != null && resp != null)
                    {
                        OnTransactionResponse(resp);
                    }
                }
                break;

            default:
                return;
            }
            handled.Set();
        }
 ///<summary>
 ///Implements IHttpModule.Init.  Hooks to Application_OnBeginRequest,
 ///Application_OnError, Application_PostRequestHandlerExecute and
 ///Application_EndRequest.
 ///</summary>
 public void Init(System.Web.HttpApplication Application)
 {
     Application.BeginRequest += new EventHandler(OnBeginRequest);
     Application.Error        += new EventHandler(CheckClose);
     Application.PostRequestHandlerExecute += new EventHandler(CheckClose);
     Application.EndRequest += new EventHandler(CheckClose);
 }
示例#24
0
        /// <summary>
        /// Called when the host application stops.
        /// </summary>
        /// <param name="application">The host application.</param>
        public void OnApplicationEnd(HttpApplication application)
        {
            Logger.Info("Better CMS host application stopped.");

            // Notify.
            ApiContext.Events.OnHostStop(application);
        }
        /// <summary>
        /// Outputs e as a SOAP fault.
        /// </summary>
        private void SoapFault(Exception e, System.Web.HttpApplication Application)
        {
            string Result = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n  <soap:Body>\r\n    <soap:Fault>\r\n      <faultcode>soap:Server</faultcode>\r\n      <faultstring>";

            if (SoapErrorMessage == "")
            {
                Result += "System.Web.Services.Protocols.SoapException: Server was unable to process request. ---&gt; ";
                while (e != null)
                {
                    Result += Application.Server.HtmlEncode(e.GetType().FullName + " : " + e.Message + "\r\n" + e.StackTrace);
                    Result += "\r\n   --- End of inner exception stack trace ---";
                    e       = e.InnerException;
                }
            }
            else
            {
                Result += Application.Server.HtmlEncode(SoapErrorMessage);
            }
            Result += "</faultstring>\r\n      <detail/>\r\n    </soap:Fault>\r\n  </soap:Body>\r\n</soap:Envelope>";
            Application.Server.ClearError();
            Application.Response.ContentType = "text/xml";
            Application.Response.Clear();
            Application.Response.Write(Result);
            Application.Response.End();
        }
        /// <summary>
        /// Error event handler that captures and logs if required any unhandled
        /// exceptions.
        /// </summary>
        private void OnError(object Source, EventArgs e)
        {
            System.Web.HttpApplication Application = (System.Web.HttpApplication)Source;
            Exception ex = Application.Server.GetLastError();

            while (ex != null &&
                   (typeof(HttpUnhandledException).IsInstanceOfType(ex) ||
                    typeof(HttpException).IsInstanceOfType(ex)) &&
                   !typeof(HttpCompileException).IsInstanceOfType(ex) &&
                   !typeof(HttpParseException).IsInstanceOfType(ex))
            {
                ex = ex.InnerException;
            }
            if (ex != null)
            {
                if (LogErrors && !Logger.IsIgnoreable(ex))
                {
                    try {
                        Logger.Log(ex, true);
                    } catch (Exception e1) { Application.Response.Write(e1.Message); Application.Response.End(); }
                }
                if (IsSoapServiceRequest(Application.Request))
                {
                    if (!typeof(SoapException).IsInstanceOfType(ex))
                    {
                        SoapFault(ex, Application);
                    }
                }
                else if (ErrorUrl != "")
                {
                    Application.Response.Redirect(ErrorUrl);
                }
            }
        }
 /// <summary>
 /// Initializes a module and prepares it to handle requests.
 /// </summary>
 /// <param name="context">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 context)
 {
     context.EndRequest += (sender, e) =>
     {
         PerWebRequestContainerProvider.DisposeCurrentScope(sender, e);
     };
 }
示例#28
0
        /// <summary>
        /// Fired from global.asax when the security module has verified that a user can access resources.
        /// </summary>
        public static void AuthorizeRequest(Object sender, EventArgs e)
        {
            System.Web.HttpApplication g = (System.Web.HttpApplication)sender;
            string p = g.Request.CurrentExecutionFilePath;

            System.Diagnostics.Trace.WriteLine("Sender: " + sender.GetType().FullName, p);
            //System.Diagnostics.Trace.WriteLine("HttpContext.Current is null = '" + (HttpContext.Current == null).ToString() + "'", p);
            //System.Diagnostics.Trace.WriteLine("HttpContext.Current.Session is null = '" + (HttpContext.Current.Session == null).ToString() + "'", p);
            // If user is authenticated then...
            if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                System.Diagnostics.Trace.WriteLine("User is authenticated", p);
                string userName = System.Web.HttpContext.Current.User.Identity.Name;
                System.Diagnostics.Trace.WriteLine("IdentityName='" + userName + "'", p);
            }
            else
            {
                System.Diagnostics.Trace.WriteLine("User is not authenticated", p);
                // ...signout.
                //System.Web.HttpContext.Current.Response.Clear();
                //System.Web.HttpContext.Current.Response.Write("Not Authenticated");
                //System.Web.HttpContext.Current.Response.End();
                //FormsAuthentication.RedirectToLoginPage();
            }
        }
示例#29
0
        private static IWebHost HostInitialization(HttpApplication application)
        {
            var kernelBuilder = new KernelBuilder();

            kernelBuilder.UseCaching(c => c.UseMemoryCache());
            kernelBuilder.UseLogging(c => c.UseNLog());
            kernelBuilder.UseWeb(c => c.EnableMvc().EnableSecurity());
            kernelBuilder.UseData(c =>
            {
                c.UseEntityFramework();
                c.EnableMvcFilterTransaction();

                //如果开启了EntityFramework的自动迁移则不启动数据迁移。
                var automaticMigrationsEnabled = ConfigurationManager.AppSettings["Data.EntityFramework.AutomaticMigrationsEnabled"];
                if (!string.Equals(automaticMigrationsEnabled, "true", StringComparison.OrdinalIgnoreCase))
                    c.EnableDataMigrators();
            });

            kernelBuilder.UseResources();

            var container = kernelBuilder.Build();

            var host = container.Resolve<IWebHost>();

            host.Initialize();
            host.BeginRequest();
            host.EndRequest();

            return host;
        }
        public void Init(HttpApplication context)
        {
            if (context == null) { throw new ArgumentNullException("context"); }

            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.EndRequest += new EventHandler(context_EndRequest);
        }
示例#31
0
 public void Init(HttpApplication context)
 {
     context.Error += context_Error;
     context.BeginRequest += context_BeginRequest;
     context.EndRequest += context_EndRequest;
     context.PostResolveRequestCache += context_PostResolveRequestCache;
 }
示例#32
0
        /// <summary>
        /// Load base settings from Database
        /// </summary>
        /// <param name="app">Context HttpApplication</param>
        public static void Start(System.Web.HttpApplication app)
        {
            if (app?.Application == null)
            {
                return;
            }

            var settings = new Settings();

            settings.LoadFromDB();
            ConfigBase.Settings = settings;

            if (Settings.IsExceptionLogEnabled)
            {
                if (settings.MainConnectionString.HasValue())
                {
                    EX.ErrorStore.Setup(settings.Name, new EX.Stores.SQLErrorStore(settings.MainConnectionString));
                }
            }

            Dapper.SqlMapper.Settings.CommandTimeout = 60;

            if (HttpContext.Current.IsDebuggingEnabled)
            {
                Dapper.SqlMapper.Settings.CommandTimeout = 30;
            }
        }
        public void Init(HttpApplication context)
        {
            //注册对于全局错误的记录
            context.Error += OnError;

            #region 记录UnhandledException

            //使用Double-Check机制保证在多线程并发下只注册一次UnhandledException处理事件
            if (!hasInitilized)
            {
                lock (syncRoot)
                {
                    if (!hasInitilized)
                    {
                        //1. 按照.net的习惯,依然首先将该内容写入到系统的EventLog中
                        string webenginePath = Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "webengine.dll");
                        //通过webengine.dll来查找asp.net的版本,eventlog的名称由asp.net+版本构成
                        if (!File.Exists(webenginePath))
                        {
                            throw new Exception(String.Format(CultureInfo.InvariantCulture, "Failed to locate webengine.dll at '{0}'.  This module requires .NET Framework 2.0.", webenginePath));
                        }

                        FileVersionInfo ver = FileVersionInfo.GetVersionInfo(webenginePath);
                        eventSourceName = string.Format(CultureInfo.InvariantCulture, "ASP.NET {0}.{1}.{2}.0", ver.FileMajorPart, ver.FileMinorPart, ver.FileBuildPart);

                        if (!EventLog.SourceExists(eventSourceName))
                        {
                            throw new Exception(String.Format(CultureInfo.InvariantCulture, "There is no EventLog source named '{0}'. This module requires .NET Framework 2.0.", eventSourceName));
                        }

                        //在出现问题后将内容记录下来
                        AppDomain.CurrentDomain.UnhandledException += (o, e) =>
                                                                          {
                                                                              if (Interlocked.Exchange(ref unhandledExceptionCount, 1) != 0)
                                                                                  return;

                                                                              string appId = (string)AppDomain.CurrentDomain.GetData(".appId");
                                                                              appId = appId ?? "No-appId";

                                                                              Exception currException;
                                                                              StringBuilder sb = new StringBuilder();
                                                                              sb.AppendLine(appId);
                                                                              for (currException = (Exception)e.ExceptionObject; currException != null; currException = currException.InnerException)
                                                                              {
                                                                                  sb.AppendFormat("{0}\n\r", currException.ToString());
                                                                                  _log.Error(currException);
                                                                              }

                                                                              EventLog eventLog = new EventLog { Source = eventSourceName };
                                                                              eventLog.WriteEntry(sb.ToString(), EventLogEntryType.Error);
                                                                          };

                        //初始化后设置该值为true保证不再继续注册事件
                        hasInitilized = true;
                    }
                }
            }

            #endregion
        }
示例#34
0
        public void Init(System.Web.HttpApplication context)
        {
            context.BeginRequest += Application_BeginRequest;
            context.EndRequest   += Application_EndRequest;

            GetDespatch = new Despatch();
        }
示例#35
0
        public void PropagatesCallerInfoThroughExceptionDuringSignaling()
        {
            var module = new TestErrorLogModule();
            var mocks = new { Context = new Mock<HttpContextBase> { DefaultValue = DefaultValue.Mock } };
            using (var app = new HttpApplication())
            {
                var context = mocks.Context.Object;
                var callerInfo = new CallerInfo("foobar", "baz.cs", 42);
                var exception = new Exception();
                IDictionary actualData = null;
                module.LogExceptionOverride = (e, _) => actualData = new Hashtable(e.Data);
                
                module.OnErrorSignaled(app, new ErrorSignalEventArgs(exception, context, callerInfo));

                Assert.Equal(0, exception.Data.Count);
                Assert.NotNull(actualData);
                Assert.Equal(1, actualData.Count);
                var actualCallerInfo = (CallerInfo) actualData.Cast<DictionaryEntry>().First().Value;
                Assert.Same(callerInfo, actualCallerInfo);

                module.LogExceptionOverride = delegate { throw new TestException(); };

                Assert.Throws<TestException>(() => module.OnErrorSignaled(app, new ErrorSignalEventArgs(exception, context, callerInfo)));
                Assert.Equal(0, exception.Data.Count);
            }
        }
示例#36
0
        /// <summary>
        /// This method is called during the module's BeginRequest event.
        /// </summary>
        /// <param name="requestedRawUrl">The RawUrl being requested (includes path and querystring).</param>
        /// <param name="app">The HttpApplication instance.</param>
        protected override void Rewrite(string requestedPath, System.Web.HttpApplication app)
        {
            // log information to the Trace object.
            //  app.//context.Trace.Write("ModuleRewriter", "Entering ModuleRewriter");

            // get the configuration rules
            RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;

            // iterate through each rule...
            for (int i = 0; i < rules.Count; i++)
            {
                // get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)
                string lookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].LookFor) + "$";

                // Create a regex (note that IgnoreCase is set...)
                Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);

                // See if a match is found
                if (re.IsMatch(requestedPath))
                {
                    // match found - do any replacement needed
                    string sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(requestedPath, rules[i].SendTo));

                    // log rewriting information to the Trace object
                    //  app.//context.Trace.Write("ModuleRewriter", "Rewriting URL to " + sendToUrl);

                    // Rewrite the URL
                    RewriterUtils.RewriteUrl(app.Context, sendToUrl);
                    break;              // exit the for loop
                }
            }

            // Log information to the Trace object
            //  app.//context.Trace.Write("ModuleRewriter", "Exiting ModuleRewriter");
        }
示例#37
0
 void IHttpModule.Init(HttpApplication context)
 {
     if (UmbracoSettings.UseViewstateMoverModule)
     {
         context.BeginRequest += new EventHandler(context_BeginRequest);
     }
 }
示例#38
0
 void ContentCache_OnLoadRequestedPath(System.Web.HttpApplication app, string sprocketPath, string[] pathSections, HandleFlag handled)
 {
     if (handled.Handled)
     {
         return;
     }
     else if (sprocketPath == "$clear-cache")
     {
         if (OnCacheClearanceRequested != null)
         {
             Result r = new Result();
             OnCacheClearanceRequested(r);
             if (!r.Succeeded)
             {
                 HttpContext.Current.Response.Write(r.Message);
                 handled.Set();
                 return;
             }
         }
         ClearCache();
         HttpContext.Current.Response.Write("The cache has been cleared.");
         handled.Set();
     }
     else if (sprocketPath == "datastore\\content-cache" || sprocketPath.StartsWith("datastore\\content-cache\\"))
     {
         handled.Set();
         HttpContext.Current.Response.Write("Access denied.");
     }
 }
 /// <summary>
 /// Sends the not authorized header.
 /// </summary>
 /// <param name="context">The context.</param>
 private void SendNotAuthorizedHeader(HttpApplication context) {
     context.Response.Clear();
     context.Response.StatusCode = 403;
     context.Response.StatusDescription = "Forbidden";
     context.Response.Write("403 Forbidden");
     context.Response.End();
 }
示例#40
0
        public void Init(HttpApplication context)
        {
            context.BeginRequest += (sender, e) =>
            {
                var request = ((HttpApplication)sender).Request;
                //TODO: By default only local requests are profiled, optionally you can set it up
                //  so authenticated users are always profiled
                //if (request.IsLocal) { MiniProfiler.Start(); }
            //                MiniProfiler.Start();
            };

            // TODO: You can control who sees the profiling information
            /*
            context.AuthenticateRequest += (sender, e) =>
            {
                if (!CurrentUserIsAllowedToSeeProfiler())
                {
                    MvcMiniProfiler.MiniProfiler.Stop(discardResults: true);
                }
            };
            */

            context.EndRequest += (sender, e) =>
            {
            //                MiniProfiler.Stop();
            };
        }
 public void Init(HttpApplication context) {
     context.BeginRequest += (sender, e) => StructuremapMvc.StructureMapDependencyScope.CreateNestedContainer();
     context.EndRequest += (sender, e) => {
         HttpContextLifecycle.DisposeAndClearAll();
         StructuremapMvc.StructureMapDependencyScope.DisposeNestedContainer();
     };
 }
示例#42
0
        public void Init(HttpApplication app)
        {
            app.BeginRequest += (sender, args) =>
            {
                var context = new HttpContextWrapper(((HttpApplication)sender).Context);

                // ReSharper disable PossibleNullReferenceException
                var decodedPath = context.Server.UrlDecode(context.Request.Url.AbsolutePath);
                // ReSharper restore PossibleNullReferenceException

                if (decodedPath == null)
                {
                    throw new HttpException((int)HttpStatusCode.BadRequest, "Bad request");
                }

                var path = decodedPath.ToLowerInvariant();

                foreach (var action in _actions.Where(action => action.CanHandle(path)))
                {
                    action.DoExecute(context, path);

                    context.ApplicationInstance.CompleteRequest();

                    break;
                }
            };
        }
示例#43
0
        /// <summary>初始化模块,准备拦截请求。</summary>
        /// <param name="context"></param>
        void IHttpModule.Init(HttpApplication context)
        {
            if (!Enable) return;

            context.BeginRequest += (s, e) => OnInit();
            //context.PostReleaseRequestState += (s, e) => OnEnd();
        }
        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += (sender, e) =>
            {
                HttpContext httpContext = ((HttpApplication)sender).Context;

                dynamic signedRequest = FacebookRequestHelpers.GetSignedRequest(
                    new HttpContextWrapper(httpContext),
                    rawSignedRequest =>
                    {
                        FacebookConfiguration config = GlobalFacebookConfiguration.Configuration;
                        FacebookClient client = config.ClientProvider.CreateClient();
                        return client.ParseSignedRequest(rawSignedRequest);
                    });

                if (signedRequest != null)
                {
                    string userId = signedRequest.user_id;
                    if (!String.IsNullOrEmpty(userId))
                    {
                        ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, userId) }));
                        Thread.CurrentPrincipal = principal;
                        httpContext.User = principal;
                    }
                }
            };
        }
 public void Init(HttpApplication context)
 {
     if (!initialized)
     {
         lock (locker)
         {
             if (!initialized)
             {
                 try
                 {
                     ApiSetup.ConfigureEntryPoints();
                     ApiSetup.RegisterRoutes();
                     initialized = true;
                 }
                 catch (Exception err)
                 {
                     if (err is TypeInitializationException && err.InnerException != null)
                     {
                         err = err.InnerException;
                     }
                     LogManager.GetLogger(GetType()).Error(err);
                 }
             }
         }
     }
 }
示例#46
0
 void Instance_OnBeforeLoadExistingFile(System.Web.HttpApplication app, string sprocketPath, string[] pathSections, HandleFlag handled)
 {
     if (sprocketPath.ToLower() == "datastore/clientspace.id")             // deny access
     {
         handled.Set();
     }
 }
示例#47
0
        //--- 利用 事件自动注册机制 来 为 当前网站的 HttpApplicaiton里的 事件 注册方法 ----------------
        //管道事件方法 的 命名规则 :一定 以 Application_事件名
        //protected void Application_BeginRequest(object sender, EventArgs e)
        //{
        //    System.Web.HttpApplication app = sender as System.Web.HttpApplication;
        //    //app.Context.Response.Write("本网站的 Global 中 自动添加的方法 ~~~~~~~~~~~!");
        //    FakeStaticProcess(app);

        //}
        /// <summary>
        /// 伪静态处理(在内部根据静态url,换成 动态url)
        /// </summary>
        /// <param name="app"></param>
        void FakeStaticProcess(System.Web.HttpApplication app)
        {
            HttpContext context = app.Context;

            context.Response.ContentType = "text/html";
            //1.获取当前静态url
            string strStaticUrl = context.Request.RawUrl;

            //context.Response.Write(context.Request.RawUrl);
            //2.解析 url
            string[] strUrlParts = strStaticUrl.Split(new char[1] {
                '/'
            }, StringSplitOptions.RemoveEmptyEntries);
            if (strUrlParts.Length > 0)
            {
                //2.1 url 开头 为 student
                if (strUrlParts[0] == "student")  // /student
                {
                    if (strUrlParts[1] == "list") //  /student/list
                    {
                    }
                    else if (strUrlParts[1] == "details")//  /student/details
                    {
                        //   /student/details/1
                        if (strUrlParts.Length == 3 && !string.IsNullOrEmpty(strUrlParts[2]))
                        {
                            //如果符合 url 则 重写 到 对应的 动态页面
                            context.RewritePath("/C03Student.aspx?id=" + strUrlParts[2]);
                        }
                    }
                }
            }

            //context.Response.End();
        }
示例#48
0
        /// <summary>
        /// Posts the authenticate request.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks>Records the web request based on the config section</remarks>
        protected void PostAuthenticateRequest(object sender, System.EventArgs args)
        {
            System.Web.HttpApplication application = sender as System.Web.HttpApplication;

            if (application != null)
            {
            }
        }
示例#49
0
        /// In the Init method register for HttpApplication events by adding your handlers
        public void Init(System.Web.HttpApplication application)
        {
            application.BeginRequest += new EventHandler(this.Application_BeginRequest);
            //application.Error += new EventHandler(this.Application_Error);

            cs   = RewriteConfigSettings.GetSettings();
            rqcs = RequestConfigSettings.GetSettings();
        }
示例#50
0
        public void Init(web.HttpApplication application)
        {
            if (cache.MemoryCache.Default.Get(_cacheName) == null)
            {
                this.RefreshCache();
            }

            application.PostAuthenticateRequest += (new EventHandler(this.Application_PostAuthenticateRequest));
        }
示例#51
0
        public bool Process301(System.Web.HttpApplication app, string sRequestedPath, bool bIsMigration)
        {
            List <URLRewriter.Config.RewriterRule> rules = RewriterConfig.Instance.lstMigrationRules;

            if (!bIsMigration)
            {
                rules = RewriterConfig.Instance.lstOldWebRules;
            }
            if (rules != null)
            {
                foreach (URLRewriter.Config.RewriterRule objRule in rules)
                {
                    string sLookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, objRule.LookFor) + "$";
                    bool   bLookForWithQueryString = sLookFor.IndexOf("\\?", StringComparison.CurrentCultureIgnoreCase) > 0;
                    if (bLookForWithQueryString)
                    {
                        sRequestedPath = app.Request.RawUrl;
                    }

                    Regex re = new Regex(sLookFor, RegexOptions.IgnoreCase);
                    if (re.IsMatch(sRequestedPath))
                    {
                        string sMoveTo = re.Replace(sRequestedPath, objRule.SendTo);
                        if (!sMoveTo.StartsWith("http"))
                        {
                            sMoveTo = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, sMoveTo);
                        }

                        //参数要带过去
                        if (!bLookForWithQueryString && app.Context.Request.QueryString.Count > 0)
                        {
                            if (sMoveTo.IndexOf('?') != -1)
                            {
                                sMoveTo += "&" + app.Context.Request.QueryString.ToString();
                            }
                            else
                            {
                                sMoveTo += "?" + app.Context.Request.QueryString.ToString();
                            }
                        }

                        if (sMoveTo.ToLower().IndexOf("/k") > 0 && sMoveTo.ToLower().IndexOf("/search/") > 0)
                        {
                            string s = sMoveTo.Substring(sMoveTo.ToLower().IndexOf("/k") + 2);
                            if (s.IndexOf("/") > 0)
                            {
                                s = s.Substring(0, s.IndexOf("/"));
                            }
                            string z = app.Server.UrlEncode(s);
                            sMoveTo = sMoveTo.Replace("/k" + s, "/k" + z);
                        }
                        return(RedirectWithCheck(sMoveTo, 301));
                    }
                }
            }
            return(false);
        }
示例#52
0
        /// <summary>
        /// Handles application "PostReleaseRequestState" event.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event arguments.</param>
        protected void Application_PostReleaseRequestState(object sender, System.EventArgs e)
        {
            System.Web.HttpApplication app = sender as System.Web.HttpApplication;

            if (Volga.Services.Streaming.ResponseFilterChain.CanApply(app.Request) && Ifly.Utils.Input.CanApplyFilterChain(app.Request, app.Response))
            {
                app.Response.Filter = new Volga.Services.Streaming.ResponseFilterChain(app.Context, app.Response.Filter);
            }
        }
示例#53
0
        public void PerformRedirect_BeginRequest(object sender, System.EventArgs args)
        {
            // see if current URL matches any redirects
            System.Web.HttpApplication application = (System.Web.HttpApplication)sender;
            string url = application.Request.Path;                                        //get the url path -- want to grab the "/folder" from the URL and compare this to

            char last = url[url.Length - 1];                                              // make sure ends is "/"

            if (Convert.ToString(last) != "/")
            {
                url += "/";
            }

            qPtl_Redirect redirect = new qPtl_Redirect(url);

            if (redirect.RedirectID > 0)
            {
                if (!String.IsNullOrEmpty(redirect.RedirectURL))
                {
                    // add log
                    int    curr_user_id     = 0;
                    string email            = application.Context.Request.QueryString["email"];
                    string campaign         = application.Context.Request.QueryString["campaign"];
                    int    curr_campaign_id = 0;

                    // try and find a user with this email address
                    if (!String.IsNullOrEmpty(email))
                    {
                        qPtl_User user = new qPtl_User(email);

                        if (user.UserID > 0)
                        {
                            curr_user_id = user.UserID;
                        }
                    }

                    qPtl_LogAction logAction = new qPtl_LogAction("View");
                    qPtl_Log       log       = new qPtl_Log();
                    log.ActorID        = curr_user_id;
                    log.Created        = DateTime.Now;
                    log.CreatedBy      = curr_user_id;
                    log.LastModified   = DateTime.Now;
                    log.LastModifiedBy = curr_user_id;
                    log.ScopeID        = 1;
                    log.LogActionID    = logAction.LogActionID;
                    log.CampaignID     = curr_campaign_id;
                    log.ReferenceID    = redirect.RedirectID;
                    log.ReferenceData  = "Email=" + email + ", Entry URL=" + redirect.EntryURL + ", RedirectURL=" + redirect.RedirectURL + ", CampaignID=" + campaign;
                    log.IPAddress      = LogUtilities.GetIPAddress();
                    log.Insert();

                    // redirect to URL
                    (sender as HttpApplication).Response.Redirect(redirect.RedirectURL, true);
                }
            }
        }
 /// <summary>
 /// OnPreRequestHandler adds a DefaultTemplate control to every page that
 /// isn't already an instance of PageTemplate and which doesn't implement
 /// INoTemplate
 /// </summary>
 private void OnPreRequestHandlerExecute(object Source, EventArgs e)
 {
     System.Web.HttpApplication Application = (System.Web.HttpApplication)Source;
     System.Web.UI.Page         Page        = Application.Context.Handler as System.Web.UI.Page;
     if (Page != null && !typeof(WebControls.PageTemplate).IsInstanceOfType(Page) &&
         !typeof(INoTemplate).IsInstanceOfType(Page))
     {
         Page.Init += new EventHandler(OnInit);
     }
 }
        public static void LoadResources(System.Web.HttpApplication application, string resourceFileList)
        {
            string[] resourceFiles = resourceFileList.Split(new char[] { ' ', ',' });
            int      priority      = 1;

            foreach (string resourceFile in resourceFiles)
            {
                MessageRepository.AddResourceFile(application.Server.MapPath("bin"), resourceFile, priority++);
            }
        }
    private void Application_BeginRequest(object sender, EventArgs e)
    {
        System.Web.HttpApplication app = (System.Web.HttpApplication)sender;
        string requestedUrl            = app.Request.Path.ToLower();
        string realUrl = GetRealUrl(requestedUrl);

        if (!String.IsNullOrEmpty(realUrl))
        {
            app.Context.RewritePath(realUrl, false);
        }
    }
示例#57
0
        void IHttpModule.Init(System.Web.HttpApplication app)
        {
            //-- Session Hack.
            //will be called before AcquireRequestState
            app.PostMapRequestHandler += new System.EventHandler(Application_PostMapRequestHandler);
            //will be called after AcquireRequestState
            app.PostAcquireRequestState += new System.EventHandler(Application_PostAcquireRequestState);
            //---

            app.AcquireRequestState += new System.EventHandler(AcquireRequestState);
            app.Error += new System.EventHandler(Application_Error);
        }
示例#58
0
        // 请求开始无法获取用户信息
        void context_BeginRequest(object sender, EventArgs e)
        {
            System.Web.HttpApplication app = (System.Web.HttpApplication)sender;
            // url rewrite
            HttpContext context  = app.Context;
            string      actionId = System.Guid.NewGuid().ToString();

            context.Response.AddHeader("ACTION-ID", actionId);
            VisitorAction action = new VisitorAction(actionId, context.Request.Url.AbsoluteUri);

            BlueFramework.User.Session.Current.PushAction(action);
        }
示例#59
0
        public void HandleHttpRequest(System.Web.HttpApplication HttpApp)
        {
            switch (HttpApp.Request.ContentType)
            {
            case "application/x-www-form-urlencoded":
            case "application/x-www-form-urlencoded; charset=UTF-8":
                ReqFactory.HttpRequestHandler(HttpApp);
                break;

            default:
                break;
            }
        }
示例#60
0
 void Instance_OnLoadRequestedPath(System.Web.HttpApplication app, string sprocketPath, string[] pathSections, HandleFlag handled)
 {
     if (sprocketPath == "scripttest")
     {
         string         html   = Sprocket.Utility.ResourceLoader.LoadTextResource("Sprocket.Web.CMS.SprocketScript.test.htm");
         SprocketScript script = new SprocketScript(html);
         HttpContext.Current.Response.ContentType = "text/html";
         script.Execute(HttpContext.Current.Response.OutputStream);
         //string test = script.Execute();
         //HttpContext.Current.Response.Write(test);
         handled.Set();
     }
 }