Ejemplo n.º 1
0
        /* stolen from the 1.0 S.W.Config ModulesConfiguration.cs */
        internal HttpModuleCollection LoadModules(HttpApplication app)
        {
            HttpModuleCollection coll = new HttpModuleCollection();
            Type type;

            foreach (HttpModuleAction item in Modules)
            {
                type = HttpApplication.LoadType(item.Type);

                if (type == null)
                {
                    /* XXX should we throw here? */
                    continue;
                }
                IHttpModule module = (IHttpModule)Activator.CreateInstance(type,
                                                                           BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                                                                           null, null, null);
                module.Init(app);
                coll.AddModule(item.Name, module);
            }

            /* XXX the 1.x config stuff does this
             * indirectly..  I'm not sure we want to do it
             * here, but this keeps things working in much
             * the same fashion in 2.0-land. */
            {
                IHttpModule module = new DefaultAuthenticationModule();
                module.Init(app);
                coll.AddModule("DefaultAuthentication", module);
            }

            return(coll);
        }
        public ImpersonationServiceInitializer(ILogProvider logProvider)
        {
            var log = logProvider.GetLogger(GetType().Name);

            log.Trace(() => "ImpersonationServiceInitializer instantianted. Creating single ImpersonationTicketExpirationModule instance.");
            _impersonationTickedExpirationModule = new ImpersonationTicketExpirationModule(logProvider);
        }
 public override void Init()
 {
     base.Init();
     foreach (string moduleName in this.Modules)
     {
         string             appName = "MYAPP";
         IHttpModule        module  = this.Modules[moduleName];
         SessionStateModule ssm     = module as SessionStateModule;
         if (ssm != null)
         {
             FieldInfo storeInfo = typeof(SessionStateModule).GetField("_store", BindingFlags.Instance | BindingFlags.NonPublic);
             SessionStateStoreProviderBase store = (SessionStateStoreProviderBase)storeInfo.GetValue(ssm);
             if (store == null)//In IIS7 Integrated mode, module.Init() is called later
             {
                 FieldInfo   runtimeInfo = typeof(HttpRuntime).GetField("_theRuntime", BindingFlags.Static | BindingFlags.NonPublic);
                 HttpRuntime theRuntime  = (HttpRuntime)runtimeInfo.GetValue(null);
                 FieldInfo   appNameInfo = typeof(HttpRuntime).GetField("_appDomainAppId", BindingFlags.Instance | BindingFlags.NonPublic);
                 appNameInfo.SetValue(theRuntime, appName);
             }
             else
             {
                 Type storeType = store.GetType();
                 if (storeType.Name.Equals("OutOfProcSessionStateStore"))
                 {
                     FieldInfo uribaseInfo = storeType.GetField("s_uribase", BindingFlags.Static | BindingFlags.NonPublic);
                     uribaseInfo.SetValue(storeType, appName);
                 }
             }
         }
     }
 }
        internal void AddModule(String name, IHttpModule m)
        {
            _all = null;
            _allKeys = null;

            BaseAdd(name, m);
        }
Ejemplo n.º 5
0
 void Pipeline_PostAuthorizeRequestStart(IHttpModule sender, HttpContext context)
 {
     if (IsRemotePath(c.Pipeline.PreRewritePath))
     {
         c.Pipeline.SkipFileTypeCheck = true;
     }
 }
Ejemplo n.º 6
0
 static void Pipeline_Rewrite(IHttpModule sender, HttpContext context, IUrlEventArgs e)
 {
     if (e.VirtualPath.StartsWith(PathUtils.ResolveAppRelative("~/photos/"), StringComparison.OrdinalIgnoreCase))
     {
         e.VirtualPath = PathUtils.ResolveAppRelative("~/App_Data/") + e.VirtualPath.Substring(PathUtils.AppVirtualPath.Length).TrimStart('/');
     }
 }
Ejemplo n.º 7
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;
                };
            }
        }
Ejemplo n.º 8
0
        public void Init(HttpApplication context)
        {
            var allKeys = context.Modules.AllKeys;
            var key     = allKeys.FirstOrDefault(x => x.Contains("InfoModule"));



            IHttpModule module = context.Modules[key];

            if (module != null && module is InfoModule)
            {
                InfoModule timerModule = (InfoModule)module;
                timerModule.RequestTimed += (src, arg) => { totalTime += arg.Duration;
                                                            requestCount++; };
            }

            context.EndRequest += (src, arg) =>
            {
                var cached = context.Context.Cache.Get("Day");
                if (cached != null && (bool)cached == false)
                {
                    context.Context.Response.Write(CreateSummary());
                }

                context.Context.Cache["day"] = false;
            };
        }
        /// <summary>
        /// Configures the <see paramref="app"/> instance and its modules.
        /// </summary>
        /// <remarks>
        /// When called, configures <see paramref="app"/> using the <see cref="IApplicationContext"/> instance
        /// provided in <paramref name="appContext"/> and the templates available in
        /// <see cref="ApplicationTemplate"/> and <see cref="ModuleTemplates"/>.
        /// </remarks>
        /// <param name="appContext">the application context instance to be used for resolving object references.</param>
        /// <param name="app">the <see cref="HttpApplication"/> instance to be configured.</param>
        public static void Configure(IConfigurableApplicationContext appContext, HttpApplication app)
        {
            IObjectDefinition applicationDefinition = s_applicationDefinition;

            if (s_applicationDefinition != null)
            {
                appContext.ObjectFactory.ConfigureObject(app, "ApplicationTemplate", applicationDefinition);
            }

            lock (s_moduleDefinitions.SyncRoot)
            {
                HttpModuleCollection modules = app.Modules;
                foreach (DictionaryEntry moduleEntry in s_moduleDefinitions)
                {
                    string            moduleName = (string)moduleEntry.Key;
                    IObjectDefinition od         = s_moduleDefinitions[moduleName];
                    IHttpModule       module     = modules[moduleName];
                    if (module != null)
                    {
                        appContext.ObjectFactory.ConfigureObject(module, moduleName, od);
                    }
                    else
                    {
                        throw ConfigurationUtils.CreateConfigurationException(string.Format("failed applying module template '{0}' - no matching module found", moduleName));
                    }
                }
            }
        }
Ejemplo n.º 10
0
 static void Pipeline_AuthorizeImage(IHttpModule sender, HttpContext context, IUrlAuthorizationEventArgs e)
 {
     if (e.VirtualPath.StartsWith(PathUtils.ResolveAppRelative("~/App_Data/photos/"), StringComparison.OrdinalIgnoreCase))
     {
         e.AllowAccess = true;
     }
 }
Ejemplo n.º 11
0
        public virtual void InitHandler(HttpApplication context, IHttpModule module = null)
        {
            Guard.CheckArgumentNull(context);
            VirtualPath = HostingEnvironment.ApplicationVirtualPath;
            if (VirtualPath == null)
            {
                return;     // Test unit
            }
            SiteAlias    = HostingEnvironment.SiteName.Replace(" ", "");
            PhysicalPath = HostingEnvironment.ApplicationPhysicalPath;

            // The first System.Exception for the current HTTP request/response process;
            Exception appError = HttpContext.Current == null ? null : HttpContext.Current.Error;

            if (appError != null && CustomError != null)
            {
                CustomError(appError);
            }

            if (module != null) // && !isModuleInit)
            {
                context.PostAuthenticateRequest += new EventHandler(OnPostAuthenticate);
                // pipeline error NullReferenceException PipelineModuleStepContainer.GetStepArray
            }
        }
Ejemplo n.º 12
0
        private void HandleHttpModule(IHttpModule module, IHttpRequest req, IHttpResponse resp)
        {
            var frontend = new FrontendHandler(req, resp);

            var handleCtx = new SimpleHttpRequestContext();

            handleCtx.Request  = req;
            handleCtx.Response = resp;

            var result = module.HandleRequest(handleCtx);

            if (result.Errors.Count > 0)
            {
                throw new AggregateException(result.Errors);
            }

            var directOutput = resp.DirectOutput;

            if (!directOutput)
            {
                var header = ServiceLocator.Current.GetInstance <IHtmlTemplate>("__header");
                frontend.WriteVars(header);

                resp.Prefix(header.Render());
            }

            if (!directOutput)
            {
                var footer = ServiceLocator.Current.GetInstance <IHtmlTemplate>("__footer");
                frontend.WriteVars(footer);

                resp.Append(footer.Render());
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Adds a route to this configuration
        /// </summary>
        /// <returns>The server configuration.</returns>
        /// <param name="route">The expression used to pre-filter requests before invoking the handler.</param>
        /// <param name="handler">The handler module that will execute the operation.</param>
        public ServerConfig AddRoute(string route, IHttpModule handler)
        {
            if (handler == null)
            {
                throw new ArgumentNullException(nameof(handler));
            }

            Router rt;

            if (this.Router == null)
            {
                this.Router = rt = new Router();
            }
            else if (this.Router is Router)
            {
                rt = this.Router as Router;
            }
            else
            {
                throw new Exception($"Cannot use the AddRoute method unless the {nameof(Router)} is an instance of {typeof(Router).FullName}");
            }

            rt.Add(route, handler);
            return(this);
        }
Ejemplo n.º 14
0
 public void FirePreHandleImageAsync(IHttpModule sender, HttpContext context, IAsyncResponsePlan e)
 {
     System.Threading.Interlocked.Increment(ref processedCount);
     if (PreHandleImageAsync != null)
     {
         PreHandleImageAsync(sender, context, e);
     }
 }
Ejemplo n.º 15
0
        void Pipeline_Rewrite(IHttpModule sender, HttpContext context, ImageResizer.Configuration.IUrlEventArgs e)
        {
            if (e.QueryString["scache"] == null) e.QueryString["scache"] = "disk";

            if (e.VirtualPath.StartsWith("/rw/", StringComparison.OrdinalIgnoreCase)) e.VirtualPath = "/s3/resizer-web" + e.VirtualPath.Substring(3);
            if (e.VirtualPath.StartsWith("/ri/", StringComparison.OrdinalIgnoreCase)) e.VirtualPath = "/s3/resizer-images" + e.VirtualPath.Substring(3);
            if (e.VirtualPath.StartsWith("/un/", StringComparison.OrdinalIgnoreCase)) e.VirtualPath = "/remote/images.unsplash.com" + e.VirtualPath.Substring(3);
        }
Ejemplo n.º 16
0
 void Pipeline_Rewrite(IHttpModule sender, HttpContext context, Configuration.IUrlEventArgs e)
 {
     //Remove 'iefix' immediately if it's not relevant so we don't slow down static requests or do needless re-encoding.
     if (!NeedsPngFix(context))
     {
         e.QueryString.Remove("iefix");
     }
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Adds a route to this configuration
 /// </summary>
 /// <returns>The server configuration.</returns>
 /// <param name="handler">The handler function that will execute the operation.</param>
 public ServerConfig AddRoute(IHttpModule handler)
 {
     if (handler == null)
     {
         throw new ArgumentNullException(nameof(handler));
     }
     return(AddRoute(null, handler));
 }
Ejemplo n.º 18
0
 public MockHttpApplication(IHttpModule module)
 {
     if (module != null)
     {
         module.Init(this);
     }
     this.module = module;
 }
Ejemplo n.º 19
0
 public void Init(HttpApplication context)
 {
     this.currentModule = ObjectService.GetObject <HttpModuleWrapperInternal>();
     if (this.currentModule != null)
     {
         this.currentModule.Init(context);
     }
 }
Ejemplo n.º 20
0
 public void Dispose()
 {
     if (this.currentModule != null)
     {
         this.currentModule.Dispose();
         this.currentModule = null;
     }
 }
Ejemplo n.º 21
0
 void Pipeline_PostRewrite(IHttpModule sender, HttpContext context, IUrlEventArgs e)
 {
     // Server-side cachebreaker
     if (e.QueryString["red_dot"] != "true" && ShouldWatermark())
     {
         e.QueryString["red_dot"] = "true";
     }
 }
Ejemplo n.º 22
0
 public MockHttpApplication(IHttpModule module, bool passNullAsSender)
 {
     if (module != null)
     {
         module.Init(this);
     }
     this.module           = module;
     this.passNullAsSender = passNullAsSender;
 }
Ejemplo n.º 23
0
        private void Pipeline_Rewrite(IHttpModule sender, HttpContext context, IUrlEventArgs e)
        {
            if (e.VirtualPath == null)
            {
                context.RewritePath("index.html");
            }

            string fileCache = ImageHelper.checkFile(e.VirtualPath);

            context.RewritePath(fileCache);



            //string root = ConfigurationManager.AppSettings["ImageRoot"] ?? String.Empty;


            //root = "~/upload/";
            //var test = VirtualPathUtility.ToAbsolute(root);
            //if (e.VirtualPath.StartsWith(VirtualPathUtility.ToAbsolute(root), StringComparison.OrdinalIgnoreCase))
            //{
            //    e.VirtualPath = Regex.Replace(e.VirtualPath,
            //        string.Format("/{root}/img/([0-9]+)\\.([0-9]+)-([^/]+)\\.(jpg|jpeg|png|gif)"),
            //        delegate(Match match)
            //        {
            //            e.QueryString["width"] = match.Groups[1].Value;
            //            e.QueryString["height"] = match.Groups[2].Value;
            //            e.QueryString["mode"] = "scale";
            //            return string.Format("/{root}/img/{match.Groups[3].Value}.{match.Groups[4].Value}");
            //        });
            //    //e.VirtualPath = Regex.Replace(e.VirtualPath, string.Format("/{root}/img/([0-9]+)w-([^/]+)\\.(jpg|jpeg|png|gif)"),
            //    //    delegate(Match match)
            //    //    {
            //    //        e.QueryString["width"] = match.Groups[1].Value;
            //    //        e.QueryString["mode"] = "scale";
            //    //        return string.Format("/{root}/img/{match.Groups[2].Value}.{match.Groups[3].Value}");
            //    //    });
            //    //e.VirtualPath = Regex.Replace(e.VirtualPath, string.Format("/{root}/img/([0-9]+)h-([^/]+)\\.(jpg|jpeg|png|gif)"),
            //    //    delegate(Match match)
            //    //    {
            //    //        e.QueryString["height"] = match.Groups[1].Value;
            //    //        e.QueryString["mode"] = "scale";
            //    //        return string.Format("/{root}/img/{match.Groups[2].Value}.{match.Groups[3].Value}");
            //    //    });

            //    context.RewritePath(e.VirtualPath);

            //}
            //else {
            //    //using V308CMS.Static.Helpers;

            //    string fileCache = ImageHelper.checkFile(e.VirtualPath);
            //    context.RewritePath(fileCache);
            //    //var fInfo = new System.IO.FileInfo(e.VirtualPath);
            //    //var result = fInfo.DirectoryName;

            //}
        }
Ejemplo n.º 24
0
        public void Init(HttpApplication context)
        {
            IHttpModule module = _module.Value;

            if (module != null)
            {
                module.Init(context);
            }
        }
Ejemplo n.º 25
0
        public void Dispose()
        {
            IHttpModule module = _module.Value;

            if (module != null)
            {
                module.Dispose();
            }
        }
Ejemplo n.º 26
0
 void Pipeline_RewriteDefaults(IHttpModule sender, HttpContext context, Configuration.IUrlEventArgs e)
 {
     //If this is IE 6 or earlier, and catchall is enabled, add iefix=true to all requests, regardless of (current) file type.
     //Rewriting rules may change the format or add it later, we'll filter to just PNG requests in PostRewrite.
     if (NeedsPngFix(context) && CatchAll)
     {
         e.QueryString["iefix"] = "true"; //If CatchAll is enabled, it's a png, and we set the default value here.
     }
 }
    public void Init(HttpApplication context)
    {
        IHttpModule httpModule    = context.Modules.Get("Session");
        var         sessionModule = httpModule as SessionStateModule;

        if (sessionModule != null)
        {
            sessionModule.Start += OnSessionStart;
        }
    }
        protected virtual void PostAuthorizeRequestStarted(IHttpModule httpModule, HttpContext httpContext)
        {
            var path = HttpUtility.UrlDecode(httpContext.Request.Url.AbsolutePath);
            if (path == null || !this._isEditModeImageUrlRegex.IsMatch(path))
            {
                return;
            }

            Config.Current.Pipeline.PreRewritePath = this._isEditModeImageUrlRegex.Match(path).Groups[1].Value;
        }
Ejemplo n.º 29
0
 void Pipeline_PreHandleImage(IHttpModule sender, HttpContext context, ImageResizer.Caching.IResponseArgs e)
 {
     if (!ImageResizer.ExtensionMethods.NameValueCollectionExtensions.Get<bool>(e.RewrittenQuerystring, "showbytes", false)) return;
     var old = e.ResizeImageToStream;
     ((ResponseArgs)e).ResizeImageToStream = delegate(Stream s) {
         MemoryStream ms = new MemoryStream(8096);
         old(ms);
         WriteTextInPng(ms.Length.ToString("N") + " bytes", s);
     };
 }
        void IHttpModule.Init(HttpApplication appContext)
        {
            IHttpModule module = appContext.Modules["Timer"];

            if (module is TimerModule timerModule)
            {
                timerModule.RequestTimed += HandleRequestTimed;
            }
            appContext.EndRequest += HandleEndRequest;
        }
        public void ShouldStartModules()
        {
            var applicationModules = new IHttpModule[]
            {
                new ModularityApplicationObserver(),
            };

            _observer.InitializeModules(applicationModules);
            _moduleMock.Verify(m => m.Initialize());
        }
        private void OnRewriteDefaults(IHttpModule sender, HttpContext context, IUrlEventArgs e)
        {
            var preset = e.QueryString["preset"];

            if (!string.IsNullOrWhiteSpace(preset) && !_presetNames.Contains(preset.ToLowerInvariant()))
            {
                throw new HttpException(404, "Not Found");
            }
            ServiceLocator.Current.GetInstance <IContentHashHelper>().RedirectIfWrongHash(new HttpContextWrapper(context), ServiceLocator.Current.GetInstance <IContentRouteHelper>().Content);
        }
Ejemplo n.º 33
0
        protected virtual void PostAuthorizeRequestStarted(IHttpModule httpModule, HttpContext httpContext)
        {
            var path  = httpContext.Request.Url.AbsolutePath;
            var split = isEditModeImageUrlRegex.Split(path);

            if (split.Length == 3)  // 3 because when a match occurs it does so at the start and end of the input
            {
                Config.Current.Pipeline.PreRewritePath = split[1];
            }
        }
Ejemplo n.º 34
0
        public static bool RegisterInPartialTrust(HttpApplication application, IHttpModule module)
        {
            if (application == null)
                throw new ArgumentNullException("application");

            if (module == null)
                throw new ArgumentNullException("module");

            if (IsHighlyTrusted())
                return false;
            
            lock (_lock)
            {
                //
                // On-demand allocate a map of modules per application.
                //

                if (_moduleListByApp == null)
                    _moduleListByApp = new Dictionary<HttpApplication, IList<IHttpModule>>();

                //
                // Get the list of modules for the application. If this is
                // the first registration for the supplied application object
                // then setup a new and empty list.
                //

                var moduleList = _moduleListByApp.Find(application);
                
                if (moduleList == null)
                {
                    moduleList = new List<IHttpModule>();
                    _moduleListByApp.Add(application, moduleList);
                }
                else if (moduleList.Contains(module))
                    throw new ApplicationException("Duplicate module registration.");

                //
                // Add the module to list of registered modules for the 
                // given application object.
                //

                moduleList.Add(module);
            }

            //
            // Setup a closure to automatically unregister the module
            // when the application fires its Disposed event.
            //

            var housekeeper = new Housekeeper(module);
            application.Disposed += housekeeper.OnApplicationDisposed;

            return true;
        }
        private void OnPostAuthorizeRequestStart(IHttpModule sender, HttpContext context)
        {
            // A hack to get ImageResizer working with images in edit mode.
            // In edit mode image URLs look like http://host.com/ui/CMS/Content/contentassets/0c51b2fa1f464956aab221c6ecc21804/file.jpg,,82777?epieditmode=False&width=100
            // For some reason, URLs that have commas in them aren't processed by ImageResizer, so they need to be removed from the end of the path.
            // Episerver can still route content even without the commas and the content ID.

            // Thumbnail URLs should not be modified, e.g. 
            // http://host.com/ui/CMS/Content/contentassets/0c51b2fa1f464956aab221c6ecc21804/file.jpg,,82777/Thumbnail?epieditmode=False?1470652477313

            var fixedUrl = PathRegex.Replace(context.Request.Url.AbsolutePath, string.Empty);
            Config.Current.Pipeline.PreRewritePath = fixedUrl;
        }
        private void OnPostAuthorizeRequestStart(IHttpModule sender, HttpContext context)
        {
            if (context.Request.Url.ToString().Contains("Thumbnail?epieditmode"))
                return;
                
            var absolutePath = CleanEditModePath(context.Request.Url.AbsolutePath);
            var resolvedContent = __urlResolver.Route(new UrlBuilder(absolutePath));

            if (resolvedContent == null)
            {
                return;
            }

            var isMediaContent = resolvedContent is MediaData;

            if (!isMediaContent)
            {
                return;
            }

            var previewOrEditMode = RequestSegmentContext.CurrentContextMode == ContextMode.Edit || RequestSegmentContext.CurrentContextMode == ContextMode.Preview;

            // Disable cache if editing or previewing
            if (!previewOrEditMode)
            {
                return;
            }

            Config.Current.Pipeline.PreRewritePath = absolutePath;
            var modifiedQueryString = new NameValueCollection(Config.Current.Pipeline.ModifiedQueryString)
            {
                {
                    "process", ProcessWhen.Always.ToString()
                },
                {
                    "cache", ServerCacheMode.No.ToString()
                }
            };

            Config.Current.Pipeline.ModifiedQueryString = modifiedQueryString;
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Add a HTTP module
        /// </summary>
        /// <param name="module">Module to include</param>
        /// <remarks>Modules are executed in the order they are added.</remarks>
        public void Add(IHttpModule module)
        {
            if (module == null) throw new ArgumentNullException("module");
            var worker = module as IWorkerModule;
            if (worker != null)
                _workerModules.Add(worker);

            var auth = module as IAuthenticationModule;
            if (auth != null)
                _authenticationModules.Add(auth);

            var auth2 = module as IAuthorizationModule;
            if (auth2 != null)
                _authorizationModules.Add(auth2);

            var routing = module as IRoutingModule;
            if (routing != null)
                _routingModules.Add(routing);

            _modules.Add(module);
        }
        private void Pipeline_PostRewrite(IHttpModule sender, HttpContext context, IUrlEventArgs e)
        {
            HttpRequest httpRequest = HttpContext.Current.Request;

            // If resolution of current screen has been passed, set maxwidth 
            // parameter for ImageResizer to handle in its pipeline
            HttpCookie httpCookie = httpRequest.Cookies.Get(ResolutionCookieKey);

            if (httpCookie != null)
            {
                e.QueryString.Add("maxwidth", httpCookie.Value);
            }

            // A cookie has not been set. If current user agent is identified 
            // as a mobile device, serve the smallest image
            else if (httpRequest.UserAgent.ToLower().Contains(UserAgentMobileSubstring))
            {
                string width = _resolutions[_resolutions.Length - 1];
                e.QueryString.Add("maxwidth", width);
            }
        }
        private void OnPostAuthorizeRequestStart(IHttpModule sender, HttpContext context)
        {
            if (context.Request.Url.ToString().Contains("Thumbnail?epieditmode"))
                return;
                
            string absolutePath = this.CleanEditModePath(context.Request.Url.AbsolutePath);
            IContent resolvedContent = __urlResolver.Route(new UrlBuilder(absolutePath));

            if (resolvedContent == null)
            {                
                return;
            }

            bool isMediaContent = resolvedContent is MediaData;

            if (!isMediaContent)
            {
                return;
            }

            Config.Current.Pipeline.SkipFileTypeCheck = true;

            bool previewOrEditMode = (
                RequestSegmentContext.CurrentContextMode == ContextMode.Edit ||
                RequestSegmentContext.CurrentContextMode == ContextMode.Preview
            );

            // Disable cache if editing or previewing
            if (previewOrEditMode)
            {
                Config.Current.Pipeline.PreRewritePath = absolutePath;
                NameValueCollection modifiedQueryString = new NameValueCollection(Config.Current.Pipeline.ModifiedQueryString);

                modifiedQueryString.Add("process", ProcessWhen.Always.ToString());
                modifiedQueryString.Add("cache", ServerCacheMode.No.ToString());
                Config.Current.Pipeline.ModifiedQueryString = modifiedQueryString;
            }                    
        }
Ejemplo n.º 40
0
        public static ICollection GetModules(HttpApplication application)
        {
            if (application == null)
                throw new ArgumentNullException("application");

            try
            {
                IHttpModule[] modules = new IHttpModule[application.Modules.Count];
                application.Modules.CopyTo(modules, 0);
                return modules;
            }
            catch (SecurityException)
            {
                //
                // Pass through because probably this is a partially trusted
                // environment that does not have access to the modules
                // collection over HttpApplication so we have to resort
                // to our own devices...
                //
            }

            lock (_lock)
            {
                if (_moduleListByApp == null)
                    return new IHttpModule[0];

                IList moduleList = (IList) _moduleListByApp[application];

                if (moduleList == null)
                    return new IHttpModule[0];

                IHttpModule[] modules = new IHttpModule[moduleList.Count];
                moduleList.CopyTo(modules, 0);
                return modules;
            }
        }
Ejemplo n.º 41
0
 static void Pipeline_Rewrite(IHttpModule sender, HttpContext context, IUrlEventArgs e)
 {
     if (e.VirtualPath.StartsWith(PathUtils.ResolveAppRelative("~/photos/"), StringComparison.OrdinalIgnoreCase))
         e.VirtualPath = PathUtils.ResolveAppRelative("~/App_Data/") + e.VirtualPath.Substring(PathUtils.AppVirtualPath.Length).TrimStart('/');
 }
Ejemplo n.º 42
0
 static void Pipeline_AuthorizeImage(IHttpModule sender, HttpContext context, IUrlAuthorizationEventArgs e)
 {
     if (e.VirtualPath.StartsWith(PathUtils.ResolveAppRelative("~/App_Data/photos/"), StringComparison.OrdinalIgnoreCase)) e.AllowAccess = true;
 }
Ejemplo n.º 43
0
        private static bool UnregisterInPartialTrust(HttpApplication application, IHttpModule module)
        {
            Debug.Assert(application != null);
            Debug.Assert(module != null);

            if (module == null)
                throw new ArgumentNullException("module");

            if (IsHighlyTrusted())
                return false;

            lock (_lock)
            {
                //
                // Get the module list for the given application object.
                //

                if (_moduleListByApp == null)
                    return false;
                
                var moduleList = _moduleListByApp.Find(application);
                
                if (moduleList == null)
                    return false;

                //
                // Remove the module from the list if it's in there.
                //

                var index = moduleList.IndexOf(module);

                if (index < 0)
                    return false;

                moduleList.RemoveAt(index);

                //
                // If the list is empty then remove the application entry.
                // If this results in the entire map becoming empty then
                // release it.
                //

                if (moduleList.Count == 0)
                {
                    _moduleListByApp.Remove(application);

                    if (_moduleListByApp.Count == 0)
                        _moduleListByApp = null;
                }
            }

            return true;
        }
Ejemplo n.º 44
0
        /*<resizer>
         * <watermarks>
         *  <otherimages path="~/watermarks" align="topleft" width="50%" />
         *  <group name="wmark">
         *   <image path="~/watermarks/image.png" align="topleft" width="50px" height="50px" />
         *  </group>
         */
        //top, left, bottom, right = px or percentages (relative to container)
        //relativeTo = image|imageArea|padding|border|margin|canvas
        //drawAs overlay|background
        //image
        //imagesettings
        //align = topleft|topright|bottomleft|bottomright|...
        void Pipeline_PostRewrite(IHttpModule sender, HttpContext context, IUrlEventArgs e)
        {
            //Cache breaking
            string[] parts = WatermarksToUse(e.QueryString);
            if (parts == null) return;

            foreach (string w in parts)
            {
                if (NamedWatermarks.ContainsKey(w))
                {
                    IEnumerable<Layer> layers = NamedWatermarks[w];
                    foreach (Layer l in layers)
                    {
                        e.QueryString["watermark-cachebreak"] = (e.QueryString["watermark-cachebreak"] ?? "") + "_" + l.GetDataHash().ToString();
                    }
                }
            }
        }
Ejemplo n.º 45
0
 public Housekeeper(IHttpModule module)
 {
     _module = module;
 }
Ejemplo n.º 46
0
 void Pipeline_PostAuthorizeRequestStart(IHttpModule sender, HttpContext context)
 {
     if (IsRemotePath(c.Pipeline.PreRewritePath)) c.Pipeline.SkipFileTypeCheck = true;
 }
Ejemplo n.º 47
0
        /*<resizer>
         * <watermarks>
         *  <otherimages path="~/watermarks" align="topleft" width="50%" />
         *  <group name="wmark">
         *   <image path="~/watermarks/image.png" align="topleft" width="50px" height="50px" />
         *  </group>
         */
        //top, left, bottom, right = px or percentages (relative to container)
        //relativeTo = image|imageArea|padding|border|margin|canvas
        //drawAs overlay|background
        //image
        //imagesettings
        //align = topleft|topright|bottomleft|bottomright|...
        void Pipeline_PostRewrite(IHttpModule sender, HttpContext context, IUrlEventArgs e)
        {
            //Cache breaking
            string watermark = e.QueryString["watermark"]; //from the querystring
            if (string.IsNullOrEmpty(watermark)) return;

            string[] parts = watermark.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string w in parts)
            {
                if (NamedWatermarks.ContainsKey(w))
                {
                    IEnumerable<Layer> layers = NamedWatermarks[w];
                    foreach (Layer l in layers)
                    {
                        e.QueryString["watermark-cachebreak"] = (e.QueryString["watermark-cachebreak"] ?? "") + "_" + l.GetDataHash().ToString();
                    }
                }
            }
        }
Ejemplo n.º 48
0
 private static void Init(HttpApplication mvcApplication, IHttpModule module)
 {
     module.Init(mvcApplication);
 }
      internal void AddModule(string key, IHttpModule m) {
         _Modules = null;
         _Keys = null;

         BaseAdd(key, m);
      }
Ejemplo n.º 50
0
		internal void AddModule (string key, IHttpModule m)
		{
			BaseAdd (key, m);
		}
Ejemplo n.º 51
0
 /// <summary>
     ///     Add a HTTP module
     /// </summary>
     /// <param name="module">Module to include</param>
     /// <remarks>Modules are executed in the order they are added.</remarks>
     public void Add(IHttpModule module)
     {
         _moduleManager.Add(module);
     }
Ejemplo n.º 52
0
 public MockHttpApplication(IHttpModule module) 
 {
     if (module != null)
     {
         module.Init(this);
     }
     this.module = module;
     
 }
Ejemplo n.º 53
0
        public static IEnumerable<IHttpModule> GetModules(HttpApplication application)
        {
            if (application == null)
                throw new ArgumentNullException("application");

            try
            {
                var modules = new IHttpModule[application.Modules.Count];
                application.Modules.CopyTo(modules, 0);
                return modules;
            }
            catch (SecurityException)
            {
                //
                // Pass through because probably this is a partially trusted
                // environment that does not have access to the modules
                // collection over HttpApplication so we have to resort
                // to our own devices...
                //
            }

            lock (registryLock)
            {
                if (moduleListByApp == null)
                    return Enumerable.Empty<IHttpModule>();

                var moduleList = moduleListByApp.Find(application);

                if (moduleList == null)
                    return Enumerable.Empty<IHttpModule>();

                var modules = new IHttpModule[moduleList.Count];
                moduleList.CopyTo(modules, 0);
                return modules;
            }
        }
Ejemplo n.º 54
0
 void Pipeline_RewriteDefaults(IHttpModule sender, HttpContext context, Configuration.IUrlEventArgs e)
 {
     //If this is IE 6 or earlier, and catchall is enabled, add iefix=true to all requests, regardless of (current) file type.
     //Rewriting rules may change the format or add it later, we'll filter to just PNG requests in PostRewrite.
     if (NeedsPngFix(context) && CatchAll) {
         e.QueryString["iefix"] = "true"; //If CatchAll is enabled, it's a png, and we set the default value here.
     }
 }
Ejemplo n.º 55
0
        /// <summary>
        /// In case there is no querystring attached to the file (thus no operations on the fly) we can
        /// redirect directly to the blob. This let us take advantage of the CDN (if configured).
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="context"></param>
        /// <param name="e"></param>
        void Pipeline_PostRewrite(IHttpModule sender, HttpContext context, Configuration.IUrlEventArgs e)
        {
            string prefix = vpp.VirtualFilesystemPrefix;

            // Check if prefix is within virtual file system and if there is no querystring
            if (e.VirtualPath.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && e.QueryString.Count == 0) {

                // Strip prefix from virtual path; keep container and blob
                string relativeBlobURL = e.VirtualPath.Substring(vPath.Length -1).Trim('/', '\\');

                // Redirect to blob
                context.Response.Redirect(blobStorageEndpoint + relativeBlobURL);
            }
        }
 public ModuleEntry(string name, IHttpModule module)
 {
     Name = name;
     Module = module;
 }
 public void AddModuleToCollection(HttpModuleCollection target, string name, IHttpModule m)
 {
     CommonReflectionUtil.MakeDelegate<Action<string, IHttpModule>>(target, this._mi_HttpModuleCollection_AddModule)(name, m);
 }
Ejemplo n.º 58
0
 void Pipeline_AuthorizeImage(IHttpModule sender, HttpContext context, IUrlAuthorizationEventArgs e)
 {
     //Don't allow direct access to the cache.
     if (e.VirtualPath.StartsWith(this.VirtualCacheDir, StringComparison.OrdinalIgnoreCase)) e.AllowAccess = false;
 }
        internal void AddModule(String name, IHttpModule m) {
            _all = null;
            _allKeys = null;

            BaseAdd(name, m);
        }
Ejemplo n.º 60
0
 public MockHttpApplication(IHttpModule module, bool passNullAsSender) 
 {
     if (module != null)
     {
         module.Init(this);
     }
     this.module = module;
     this.passNullAsSender = passNullAsSender;
 }