public static HttpContextBase GetFakeContext()
        {
            var httpContext = MockRepository.GenerateStub<HttpContextBase>();
            var request = MockRepository.GenerateStub<HttpRequestBase>();
            var response = MockRepository.GenerateStub<HttpResponseBase>();
            var session = MockRepository.GenerateStub<HttpSessionStateBase>();
            var server = MockRepository.GenerateStub<HttpServerUtilityBase>();
            var cookies = new HttpCookieCollection();

            httpContext.Stub(x => x.Request)
                .Return(request);
            httpContext.Stub(x => x.Response)
                .Return(response);
            httpContext.Stub(x => x.Session)
                .Return(session);
            httpContext.Stub(x => x.Server)
                .Return(server);
            response.Stub(x => x.Cookies)
                .Return(cookies);

            var writer = new StringWriter();
            var wr = new SimpleWorkerRequest("", "", "", "", writer);
            HttpContext.Current = new HttpContext(wr);

            return httpContext;
        }
        public string AspxToString(string aspx)
        {
            StringBuilder sb = new StringBuilder();
            using (StringWriter sw = new StringWriter(sb))
            {
                using (HtmlTextWriter tw = new HtmlTextWriter(sw))
                {
                    var workerRequest = new SimpleWorkerRequest(aspx, "", tw);
                    HttpContext.Current = new HttpContext(workerRequest);

                    object view = BuildManager.CreateInstanceFromVirtualPath(aspx, typeof(object));

                    Page viewPage = view as Page;
                    if (viewPage == null)
                    {
                        UserControl viewUserControl = view as UserControl;
                        if (viewUserControl != null)
                        {
                            viewPage = new Page();
                            viewPage.Controls.Add(viewUserControl);
                        }
                    }

                    if (viewPage != null)
                    {
                        HttpContext.Current.Server.Execute(viewPage, tw, true);

                        return sb.ToString();
                    }

                    throw new InvalidOperationException();
                }
            }
        }
        public void CropImage()
        {
            // Arrange
            PassPhotoController mycontroller = new PassPhotoController();

            // Use Mock the Request Object that is used on Index
            Mock<ControllerContext> cc = new Mock<ControllerContext>();
            cc.Setup(d => d.HttpContext.Request.Path).Returns("/");
            String imgfolder = mytestutils.GetLocalRootPathToFile("\\uploaded_images\\");
            mycontroller.ControllerContext = cc.Object;

            SimpleWorkerRequest request = new SimpleWorkerRequest("", "", "", null, new StringWriter());
            HttpContext context = new HttpContext(request);
            HttpContext.Current = context;

            // Get full path to js file that is used in the controller
            String localjsfile = mytestutils.GetLocalRootPathToFile("\\js\\tiffjcroppreset.js");

            // Act
            ViewResult result = mycontroller.CropImage("testimage2.jpg", "raw", "0", "0", "220", "280", imgfolder, localjsfile) as ViewResult;

            Boolean isFileCropped = File.Exists(mytestutils.GetLocalRootPathToFile("\\uploaded_images\\cropped\\") + "testimage2.jpg");

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.ViewBag.Height);
            Assert.IsNotNull(result.ViewBag.Width);
            Assert.IsNotNull(result.ViewBag.PreviewJSMarkup);
            Assert.IsNotNull(result.ViewBag.RootPath);
            Assert.IsNotNull(result.ViewBag.ImageName);
            Assert.IsNotNull(result.ViewBag.ImageUrl);
            Assert.IsNotNull(result.ViewBag.PreviewDisplay);
            Assert.IsTrue(isFileCropped);
        }
 /// <summary>
 /// </summary>
 /// <param name="filename">
 /// </param>
 /// <param name="queryString">
 /// </param>
 /// <returns>
 /// </returns>
 private string ProcessFile(string filename, string queryString)
 {
     var sw = new StringWriter();
     var simpleWorker = new SimpleWorkerRequest(filename, queryString, sw);
     HttpRuntime.ProcessRequest(simpleWorker);
     return sw.ToString();
 }
        public TestWebContext(string virtualPath, string page)
        {
            _out = new StringWriter();
            HttpWorkerRequest wr;
            AppDomain domain = Thread.GetDomain();

            // are we running within a valid AspNet AppDomain?
            string appPath = (string) domain.GetData(".appPath");
            if (appPath != null)
            {
                wr = new SimpleWorkerRequest(page, string.Empty, _out);
            }
            else
            {
                appPath = domain.BaseDirectory + "\\";
                wr = new SimpleWorkerRequest(virtualPath, appPath, page, string.Empty, _out);
            }
            HttpContext ctx = new HttpContext(wr);
            HttpContext.Current = ctx;
            HttpBrowserCapabilities browser = new HttpBrowserCapabilities();
            browser.Capabilities = new CaseInsensitiveHashtable(); //CollectionsUtil.CreateCaseInsensitiveHashtable();
            browser.Capabilities[string.Empty] = "Test User Agent"; // string.Empty is the key for "user agent"

            // avoids NullReferenceException when accessing HttpRequest.FilePath
            object virtualPathObject = ExpressionEvaluator.GetValue(null, "T(System.Web.VirtualPath).Create('/')");
            object cachedPathData = ExpressionEvaluator.GetValue(null, "T(System.Web.CachedPathData).GetRootWebPathData()");
            ExpressionEvaluator.SetValue(cachedPathData, "_virtualPath", virtualPathObject);
            ExpressionEvaluator.SetValue(cachedPathData, "_physicalPath", appPath);

            ctx.Request.Browser = browser;
            string filePath = ctx.Request.FilePath;
            _wr = wr;
        }
		static void Main(string[] args) {
			// Create the application host
			object host = ApplicationHost.CreateApplicationHost(typeof(MyHost), "/", "c:\\");
			
			int request_count = 10;
			SimpleWorkerRequest [] requests = new SimpleWorkerRequest[request_count];

			int pos;
			for (pos = 0; pos != request_count; pos++) {
				requests[pos] = new SimpleWorkerRequest("test.aspx", "", Console.Out);
			}

			ModulesConfiguration.Add("syncmodule", typeof(SyncModule).AssemblyQualifiedName);
			ModulesConfiguration.Add("asyncmodule", typeof(AsyncModule).AssemblyQualifiedName);
			
			HandlerFactoryConfiguration.Add("get", "/", typeof(AsyncHandler).AssemblyQualifiedName);
			//HandlerFactoryConfiguration.Add("get", "/", typeof(SyncHandler).AssemblyQualifiedName);

			for (pos = 0; pos != request_count; pos++) 
				HttpRuntime.ProcessRequest(requests[pos]);

			HttpRuntime.Close();
/*
			Console.Write("Press Enter to quit.");
			Console.WriteLine();
			Console.ReadLine();
*/
		}	
Exemple #7
0
 private static HttpApplication GetApplicationInstance()
 {
     var writer = new StringWriter();
       var workerRequest = new SimpleWorkerRequest("", "", writer);
       var httpContext = new HttpContext(workerRequest);
       return (HttpApplication)getApplicationInstanceMethod.Invoke(null, new object[] { httpContext });
 }
        public void Index()
        {
            // Arrange
            PassPhotoController mycontroller = new PassPhotoController();

            // Use Mock the Request Object that is used on Index
            Mock<ControllerContext> cc = new Mock<ControllerContext>();
            cc.Setup(d => d.HttpContext.Request.Path).Returns("/");
            cc.Setup(e => e.HttpContext.Server.MapPath("~/js/tiffjcroppreset.js")).Returns(mytestutils.GetLocalRootPathToFile("\\js\\tiffjcroppreset.js"));
            mycontroller.ControllerContext = cc.Object;

            SimpleWorkerRequest request = new SimpleWorkerRequest("", "", "", null, new StringWriter());
            HttpContext context = new HttpContext(request);
            HttpContext.Current = context;

            // Get full path to js file that is used in the controller
            String localjsfile = mytestutils.GetLocalRootPathToFile("\\js\\tiffjcroppreset.js");

            // Act
            ViewResult result = mycontroller.Index(localjsfile) as ViewResult;

            // Assert
            Assert.IsNotNull(result);
            Assert.IsNotNull(result.ViewBag.Height);
            Assert.IsNotNull(result.ViewBag.Width);
            Assert.IsNotNull(result.ViewBag.PreviewJSMarkup);
            Assert.IsNotNull(result.ViewBag.RootPath);
        }
 public static void SetHttpContext()
 {
     SimpleWorkerRequest simpleWorkerRequest = new SimpleWorkerRequest(string.Empty, string.Empty, string.Empty, null, new StringWriter());
     HttpContext.Current = new HttpContext(simpleWorkerRequest);
     HttpContext.Current.Request.Cookies.Add(new HttpCookie(UserRequestModel_Keys.WcfClientCultureSelectedCookieName, currentCultureName));
     Thread.CurrentThread.CurrentCulture = GlobalizationHelper.CultureInfoGetOrDefault(currentCultureName);
 }
Exemple #10
0
		public void FixtureSetUp ()
		{
			// we're at full trust here
			sw = new StringWriter ();
			cwd = Environment.CurrentDirectory;
			swr = new SimpleWorkerRequest ("/", cwd, String.Empty, String.Empty, sw);
		}
        public void GetFilePathTranslatedTest()
        {
            SimpleWorkerRequest reference = new SimpleWorkerRequest("/webapp", "c:\\webapp\\", "default.aspx", "", null);

            AspNetWorker worker = GetHttpWorker("/webapp", "c:\\webapp\\");
            Assert.AreEqual(reference.GetFilePathTranslated(), worker.GetFilePathTranslated());
        }
 public void CreateHtmlPage(String webPage, 
     String query)
 {
     SimpleWorkerRequest swr = new SimpleWorkerRequest(webPage,
                                                       query,
                                                       Console.Out);
     HttpRuntime.ProcessRequest(swr);
 }
		//
		// This tests the constructor when the user code creates an HttpContext
		//
		[Test] public void ConstructorTests ()
		{
			StringWriter sw = new StringWriter ();
			
			SimpleWorkerRequest swr;

			swr = new SimpleWorkerRequest ("/appVirtualDir", cwd, "pageVirtualPath", "querystring", sw);
			Assert.AreEqual ("/appVirtualDir", swr.GetAppPath (), "S1");
			Assert.AreEqual ("/appVirtualDir/pageVirtualPath", swr.GetFilePath (), "S2");
			Assert.AreEqual ("GET", swr.GetHttpVerbName (), "S3");
			Assert.AreEqual ("HTTP/1.0", swr.GetHttpVersion (), "S4");
			Assert.AreEqual ("127.0.0.1", swr.GetLocalAddress (), "S5");
			Assert.AreEqual (80, swr.GetLocalPort (), "S6");
			Assert.AreEqual ("querystring", swr.GetQueryString (), "S7");
			Assert.AreEqual ("127.0.0.1", swr.GetRemoteAddress (), "S8");
			Assert.AreEqual (0, swr.GetRemotePort (), "S9");
			Assert.AreEqual ("/appVirtualDir/pageVirtualPath?querystring", swr.GetRawUrl (), "S10");
			Assert.AreEqual ("/appVirtualDir/pageVirtualPath", swr.GetUriPath (), "S11");
			Assert.AreEqual ("0", swr.GetUserToken ().ToString (), "S12");
			Assert.AreEqual (null, swr.MapPath ("x"), "S13");
			Assert.AreEqual (null, swr.MachineConfigPath, "S14");
			Assert.AreEqual (null, swr.MachineInstallDirectory, "S15");
			Assert.AreEqual (Path.Combine (cwd, "pageVirtualPath"), swr.GetFilePathTranslated (), "S16");
			Assert.AreEqual ("", swr.GetServerVariable ("AUTH_TYPE"), "S18");
			Assert.AreEqual ("", swr.GetServerVariable ("AUTH_USER"), "S19");
			Assert.AreEqual ("", swr.GetServerVariable ("REMOTE_USER"), "S20");
			Assert.AreEqual ("", swr.GetServerVariable ("SERVER_SOFTWARE"), "S21");
			Assert.AreEqual ("/appVirtualDir/pageVirtualPath", swr.GetUriPath (), "S22");

			//
			// MapPath
			//
			Assert.AreEqual (null, swr.MapPath ("file.aspx"), "MP1");
			Assert.AreEqual (null, swr.MapPath ("/appVirtualDir/pageVirtualPath"), "MP2");
			Assert.AreEqual (null, swr.MapPath ("appVirtualDir/pageVirtualPath"), "MP3");
			Assert.AreEqual (null, swr.MapPath ("/appVirtualDir/pageVirtualPath/page.aspx"), "MP4");
			Assert.AreEqual (null, swr.MapPath ("/appVirtualDir/pageVirtualPath/Subdir"), "MP5");

			swr = new SimpleWorkerRequest ("/appDir", cwd, "/Something/page.aspx", "querystring", sw);

			//Assert.AreEqual ("c:\\tmp\\page.aspx", swr.GetFilePathTranslated (), "S17");

			//
			// GetUriPath tests, veredict: MS implementation is a bit fragile on this interface
			//
			swr = new SimpleWorkerRequest ("/appDir", cwd, "/page.aspx", null, sw);
			Assert.AreEqual ("/appDir//page.aspx", swr.GetUriPath (), "S23");

			swr = new SimpleWorkerRequest ("/appDir/", cwd, "/page.aspx", null, sw);
			Assert.AreEqual ("/appDir///page.aspx", swr.GetUriPath (), "S24");

			swr = new SimpleWorkerRequest ("/appDir/", cwd, "page.aspx", null, sw);
			Assert.AreEqual ("/appDir//page.aspx", swr.GetUriPath (), "S25");

			swr = new SimpleWorkerRequest ("/appDir", cwd, "page.aspx", null, sw);
			Assert.AreEqual ("/appDir/page.aspx", swr.GetUriPath (), "S26");
			
		}
 private FakeHttpContext()
 {
     var request = new SimpleWorkerRequest("/test", @"c:\inetpub", "test.html", null, Console.Out);
     var context = new HttpContext(request);
     var stateContainer = new HttpSessionStateContainer(Guid.NewGuid().ToString(), new SessionStateItemCollection(),
                                                                   new HttpStaticObjectsCollection(), 60000, false, HttpCookieMode.UseCookies,
                                                                   SessionStateMode.InProc, false);
     SessionStateUtility.AddHttpSessionStateToContext(context, stateContainer);
     HttpContext.Current = context;
 }
        public void GetAppPoolIDTest()
        {
            /*
             * This test was ignored because I fail to find it useful at the moment.
             */
            SimpleWorkerRequest reference = new SimpleWorkerRequest("/webapp", "c:\\webapp\\", "default.aspx", "", null);

            AspNetWorker worker = GetHttpWorker("/webapp", "c:\\webapp\\");
            Assert.AreEqual(reference.GetAppPoolID(), worker.GetAppPoolID());
        }
        public static void CreateHttpContext()
        {
            if (HttpContext.Current != null)
                return;

            TextWriter tw = new StringWriter();
            HttpWorkerRequest wr = new SimpleWorkerRequest("/webappt", "c:\\inetpub\\wwwroot\\webapp\\", "default.aspx",
                                                           "", tw);
            HttpContext.Current = new HttpContext(wr);
            HttpContext.Current.User = new GenericPrincipal(new GenericIdentity("testuser"), null);
        }
Exemple #17
0
        public string CreateRequest(string page, string query)
        {
            StringWriter writer;
            SimpleWorkerRequest worker;

            writer = new StringWriter();
            worker = new SimpleWorkerRequest(page, query, writer);
            HttpRuntime.ProcessRequest(worker);
            writer.Flush();

            return writer.GetStringBuilder().ToString();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MockHttpContext"/> class using the specified application path and virtual directory.
        /// </summary>
        /// <param name="applicationPath"></param>
        /// <param name="virtualDirectory"></param>
        /// <param name="page"></param>
        /// <param name="query"></param>
        public MockHttpContext(string applicationPath, string virtualDirectory, string page, string query)
        {
            if (String.IsNullOrWhiteSpace(applicationPath))
             {
            throw new ArgumentException("Application path is empty!", "applicationPath");
             }

             if (String.IsNullOrWhiteSpace(virtualDirectory))
             {
            throw new ArgumentException("Virtual directory path is empty!", "virtualDirectory");
             }

             _applicationPath = applicationPath;
             _virtualDirectory = virtualDirectory;

             _currentContext = HttpContext.Current;

             if (null == HttpContext.Current)
             {
            AppDomain.CurrentDomain.SetData(".appDomain", "*");
            AppDomain.CurrentDomain.SetData(".appPath", applicationPath);
            AppDomain.CurrentDomain.SetData(".appVPath", virtualDirectory);
            AppDomain.CurrentDomain.SetData(".hostingVirtualPath", virtualDirectory);
            AppDomain.CurrentDomain.SetData(".hostingInstallDir", HttpRuntime.AspInstallDirectory);
            TextWriter tw = new StringWriter();
             var simpleWorkerRequest = new SimpleWorkerRequest(page, query, tw);

             HttpWorkerRequest wr = simpleWorkerRequest;
            HttpContext.Current = new HttpContext(wr);

            _sessionData = new SessionItem();
            _sessionData.Items = new SessionStateItemCollection();
            _sessionData.StaticObjects = SessionStateUtility.GetSessionStaticObjects(HttpContext.Current);
            _sessionID = Guid.NewGuid().ToString();

            _ioLock.EnterWriteLock();

            try
            {
               _sessionItems.Add(_sessionID, _sessionData);
            }
            finally
            {
               _ioLock.ExitWriteLock();
            }

            var container = new HttpSessionStateContainer(_sessionID, _sessionData.Items, _sessionData.StaticObjects, 10,
                                                          true, _cookieMode, SessionStateMode.Custom, false);
            SessionStateUtility.AddHttpSessionStateToContext(HttpContext.Current, container);
             }
        }
 public void processHttpContext(NotifierHttpContext notifierHttpContext)
 {
     try {
     TextWriter          tw = new StringWriter ();
     SimpleWorkerRequest wrq = new SimpleWorkerRequest ("/", ".", "url", "", tw);
     HttpContext         httpContext = new HttpContext (wrq);
     log ("processHttpContext before");
     notifierHttpContext (httpContext);
     log ("process0HttpContext after");
       }
       catch (Exception ex) {
     Console.WriteLine ("Exception: {0}", ex);
       }
 }
 public string ExecuteMvcUrl(string url, string query)
 {
     var writer = new StringWriter();
     var request = new SimpleWorkerRequest(url, query, writer);
     var context = HttpContext.Current = new HttpContext(request);
     var contextBase = new HttpContextWrapper(context);
     var routeData = RouteTable.Routes.GetRouteData(contextBase);
     var routeHandler = routeData.RouteHandler;
     var requestContext = new RequestContext(contextBase, routeData);
     var httpHandler = routeHandler.GetHttpHandler(requestContext);
     httpHandler.ProcessRequest(context);
     context.Response.End();
     writer.Flush();
     return writer.GetStringBuilder().ToString();
 }
        public void PerWebRequestLifestyleManagerTest() {
            var tw = new StringWriter();
            var wr = new SimpleWorkerRequest("/", Directory.GetCurrentDirectory(), "default.aspx", null, tw);
            var module = new PerWebRequestLifestyleModule();

            var ctx = HttpModuleRunner.GetContext(wr, new[] { module });
            HttpContext.Current = ctx.Key;

            using (var kernel = new DefaultKernel()) {
                kernel.Register(Component.For<object>().LifeStyle.PerWebRequest);
                var instance1 = kernel.Resolve<object>();
                Assert.IsNotNull(instance1);
                var instance2 = kernel.Resolve<object>();
                Assert.IsNotNull(instance2);
                Assert.AreSame(instance1, instance2);
            }
        }
        public void HttpContextProviderTest()
        {
            //create a fake http request.
            SimpleWorkerRequest request = new SimpleWorkerRequest("","","", null, new StringWriter());
            HttpContext context = new HttpContext(request);
            HttpContext.Current = context;

            var var2 = new TlsHelper<string>("var2", () => "initial");

            //test that the TLS helper picked the right provider and is storing values correctly.
            Assert.AreEqual(typeof(Providers.HttpContextProvider<string>), var2.Provider.GetType());
            Assert.AreEqual(var2.Value, "initial");

            var2.Value = "New Value";

            Assert.AreEqual(var2.Value, "New Value");
        }
		protected override void Initialize()
		{
			if (_aspNetHost == null)
			{
				lock (_lockObj)
				{
					if (_aspNetHost == null)
					{
						SandboxHelper.ExecuteInFullTrust(
							() =>
							{
								var aspNetRootFolder = WorkerConfiguration.Current.AspNetRootFolder;
								if (!aspNetRootFolder.EndsWith("\\"))
									aspNetRootFolder += "\\";

								CopySiteRoot(aspNetRootFolder);

								string virtualFolder = "/MvcPageAction/" + WorkerConfiguration.Current.ID + "/";

								_aspNetHost = new AspNetHost(aspNetRootFolder, virtualFolder);

								try
								{
									_aspNetHost.Start();
								}
								catch (Exception ex)
								{
									ex.ToString();
									throw;
								}
								HostingEnvironment.RegisterVirtualPathProvider(new FakeVirtualPathProvider());

								// we just do empty request to not existing file, so Asp.Net would initialize Http Application in full trust, and next request can be processed in sandbox
								StringWriter writer = new StringWriter();
								SimpleWorkerRequest worker = new SimpleWorkerRequest("static/Warmup.aspx", null, writer);
								HttpRuntime.ProcessRequest(worker);
								writer.Flush();

								string html = writer.ToString();
								html.ToString();
							});
					}
				}
			}
			base.Initialize();
		}
        public MockHttpContext(string page, string query)
        {
            Thread.GetDomain().SetData( ThreadDataKeyAppPath, ThreadDataKeyAppPathValue);
            Thread.GetDomain().SetData( ThreadDataKeyAppVPath, ThreadDataKeyAppVPathValue);

            SimpleWorkerRequest request = new SimpleWorkerRequest(page, query, new StringWriter());
            _context = new HttpContext(request);

            HttpSessionStateContainer container = new HttpSessionStateContainer( Guid.NewGuid().ToString("N"), new SessionStateItemCollection(), 
                                                        new HttpStaticObjectsCollection(), 5, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, 
                                                        false);

            HttpSessionState state = Activator.CreateInstance( typeof(HttpSessionState), 
                                        BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance,
                                        null, new object[] { container }, CultureInfo.CurrentCulture) as HttpSessionState;
            _context.Items["AspSession"] = state;
        }
        public void tt()
        {
            var tw = new StringWriter();
            var wr = new SimpleWorkerRequest("/", Directory.GetCurrentDirectory(), "default.aspx", null, tw);
            var module = new PerWebRequestLifestyleModule();

            var ctx = HttpModuleRunner.GetContext(wr, new[] {module});
            HttpContext.Current = ctx.Key;

            var container = new WindsorContainer(new MockProxyFactory());
            container.Kernel.ComponentDestroyed += Kernel_ComponentDestroyed;
            container.AddComponentLifeStyle<SomeComponent>(LifestyleType.PerWebRequest);
            var c1 = container.Resolve<SomeComponent>();
            HttpModuleRunner.ProcessRequest(ctx.Value, ctx.Key);
            container.Release(c1);
            var c2 = container.Resolve<SomeComponent>();
            Assert.AreNotSame(c1, c2);
        }
        public void InitializeApplication(IntPtr appContext)
        {
            s_ApplicationContext = appContext;
            HttpApplication app = null;

            try
            {
                HttpRuntime.UseIntegratedPipeline = true;
                if (!HttpRuntime.HostingInitFailed)
                {
                    HttpWorkerRequest wr      = new SimpleWorkerRequest("", "", new StringWriter(CultureInfo.InvariantCulture));
                    HttpContext       context = new HttpContext(wr);
                    app = HttpApplicationFactory.GetPipelineApplicationInstance(appContext, context);
                }
            }
            catch (Exception exception)
            {
                if (HttpRuntime.InitializationException == null)
                {
                    HttpRuntime.InitializationException = exception;
                }
            }
            finally
            {
                s_InitializationCompleted = true;
                if (HttpRuntime.InitializationException != null)
                {
                    int errorCode = UnsafeIISMethods.MgdRegisterEventSubscription(appContext, "AspNetInitializationExceptionModule", RequestNotification.BeginRequest, 0, "AspNetInitializationExceptionModule", "", new IntPtr(-1), false);
                    if (errorCode < 0)
                    {
                        throw new COMException(System.Web.SR.GetString("Failed_Pipeline_Subscription", new object[] { "AspNetInitializationExceptionModule" }), errorCode);
                    }
                    errorCode = UnsafeIISMethods.MgdRegisterEventSubscription(appContext, "ManagedPipelineHandler", RequestNotification.ExecuteRequestHandler, 0, string.Empty, "managedHandler", new IntPtr(-1), false);
                    if (errorCode < 0)
                    {
                        throw new COMException(System.Web.SR.GetString("Failed_Pipeline_Subscription", new object[] { "ManagedPipelineHandler" }), errorCode);
                    }
                }
                if (app != null)
                {
                    HttpApplicationFactory.RecyclePipelineApplicationInstance(app);
                }
            }
        }
	   public string ProcessRequest(string page)	
	   {
	   		O2Gui.open<System.Windows.Forms.Panel>("Util - LogViewer", 400,140).add_LogViewer();
	   		"Current Directory: {0}".info(Environment.CurrentDirectory);
	   		
	   		var o2Timer = new O2Timer("ProcessRequest for file: {0}".info(page)).start();			
	   		Page = page ?? Page;
			var stringWriter = new StringWriter();
		   	simpleWorkerRequest = new SimpleWorkerRequest(Page, string.Empty, stringWriter);
		   	
		   	//openScript();
		   	
		   	//"Good Morning".execute_InScriptEditor_InSeparateAppDomain();
		   	"processing request for: {0}".info(Page);
		   	HttpRuntime.ProcessRequest(simpleWorkerRequest);
		   	var Html = stringWriter.str();
		   	o2Timer.stop();
		   	return Html;	
	   }	   	   	   	
Exemple #28
0
        public static HttpContextBase FakeHttpContext()
        {
            var context = new Mock<HttpContextBase>();
            var request = new Mock<HttpRequestBase>();
            var response = new Mock<HttpResponseBase>();
            var session = new Mock<HttpSessionStateBase>();
            var server = new Mock<HttpServerUtilityBase>();

            context.Setup(ctx => ctx.Request).Returns(request.Object);
            context.Setup(ctx => ctx.Response).Returns(response.Object);
            context.Setup(ctx => ctx.Session).Returns(session.Object);
            context.Setup(ctx => ctx.Server).Returns(server.Object);

            var writer = new StringWriter();
            var wr = new SimpleWorkerRequest("", "", "", "", writer);
            HttpContext.Current = new HttpContext(wr);

            return context.Object;
        }
        public void With_context_uses_context() {
            var tw = new StringWriter();
            var wr = new SimpleWorkerRequest("/", Directory.GetCurrentDirectory(), "default.aspx", null, tw);
            var module = new PerWebRequestLifestyleModule();

            var ctx = HttpModuleRunner.GetContext(wr, new[] { module });
            HttpContext.Current = ctx.Key;

            using (var k = new DefaultKernel()) {
                k.Register(Component.For<Dummy>().LifeStyle.HybridPerWebRequestTransient());
                var d1 = k.Resolve<Dummy>();
                Assert.IsNotNull(d1);
                var d2 = k.Resolve<Dummy>();
                Assert.IsNotNull(d2);
                Assert.AreSame(d1, d2);
                ctx.Value.FireEndRequest();
                ctx.Key.Items["castle.per-web-request-lifestyle-cache"] = null;
                var d3 = k.Resolve<Dummy>();
                Assert.AreNotSame(d1, d3);
            }
        }
Exemple #30
0
        public HttpContextProxy(String fileName, String queryString)
            : base()
        {
            MemoryStream responseStream = new MemoryStream();
            TextWriter responseWriter = new StreamWriter(responseStream);
            HttpWorkerRequest wr = new SimpleWorkerRequest("/", @"C:\inetpub\wwwroot\", fileName, queryString, responseWriter);
            HttpContext context = new HttpContext(wr);
            HttpBrowserCapabilities browser = new HttpBrowserCapabilities();
            browser.SetFieldValue("_items", new Hashtable());
            context.Request.Browser = browser;

            HttpContext previousContext = HttpContext.Current;
            HttpContext.Current = context;

            this._context = context;
            this._previousContext = previousContext;
            this._responseStream = responseStream;
            this._responseWriter = responseWriter;

            IHttpSessionState container = new HttpSessionStateContainer(Guid.NewGuid().ToString(), new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 20, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false);
            this.SetSessionState(container);
        }
        public void Setup()
        {
            var request = new SimpleWorkerRequest("", "", "", null, new StringWriter());
            var context = new HttpContext(request);
            //context.
            //HttpContext.Current = context;

            kernel = new StandardKernel(new TestServiceModule());
            DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));

            accountRepository = new AccountRepository();
            accountGroupsRepository = new AccountGroupsRepository();
            dealerRepository = new DealerRepository();
            positionRepository = new PositionRepository();
        }
        public void InitializeApplication(IntPtr appContext)
        {
            s_ApplicationContext = appContext;

            // DevDiv #381425 - webengine4!RegisterModule runs *after* HostingEnvironment.Initialize (and thus the
            // HttpRuntime static ctor) when application preload is active. This means that any global state set
            // by RegisterModule (like the IIS version information, whether we're in integrated mode, misc server
            // info, etc.) will be unavailable to PreAppStart / preload code when the preload feature is active.
            // But since RegisterModule runs before InitializeApplication, we have one last chance here to collect
            // the information before the main part of the application starts, and the pipeline can depend on it
            // to be accurate.
            HttpRuntime.PopulateIISVersionInformation();

            HttpApplication app = null;

            try {
                // if HttpRuntime.HostingInit failed, do not attempt to create the application (WOS #1653963)
                if (!HttpRuntime.HostingInitFailed)
                {
                    //
                    //  On IIS7, application initialization does not provide an http context.  Theoretically,
                    //  no one should be using the context during application initialization, but people do.
                    //  Create a dummy context that is used during application initialization
                    //  to prevent breakage (ISAPI mode always provides a context)
                    //
                    HttpWorkerRequest initWorkerRequest = new SimpleWorkerRequest("" /*page*/,
                                                                                  "" /*query*/,
                                                                                  new StringWriter(CultureInfo.InvariantCulture));
                    MimeMapping.SetIntegratedApplicationContext(appContext);
                    HttpContext initHttpContext = new HttpContext(initWorkerRequest);
                    app = HttpApplicationFactory.GetPipelineApplicationInstance(appContext, initHttpContext);
                }
            }
            catch (Exception e)
            {
                if (HttpRuntime.InitializationException == null)
                {
                    HttpRuntime.InitializationException = e;
                }
            }
            finally {
                s_InitializationCompleted = true;

                if (HttpRuntime.InitializationException != null)
                {
                    // at least one module must be registered so that we
                    // call ProcessRequestNotification later and send the formatted
                    // InitializationException to the client.
                    int hresult = UnsafeIISMethods.MgdRegisterEventSubscription(
                        appContext,
                        InitExceptionModuleName,
                        RequestNotification.BeginRequest,
                        0 /*postRequestNotifications*/,
                        InitExceptionModuleName,
                        s_InitExceptionModulePrecondition,
                        new IntPtr(-1),
                        false /*useHighPriority*/);

                    if (hresult < 0)
                    {
                        throw new COMException(SR.GetString(SR.Failed_Pipeline_Subscription, InitExceptionModuleName),
                                               hresult);
                    }

                    // Always register a managed handler:
                    // WOS 1990290: VS F5 Debugging: "AspNetInitializationExceptionModule" is registered for RQ_BEGIN_REQUEST,
                    // but the DEBUG verb skips notifications until post RQ_AUTHENTICATE_REQUEST.
                    hresult = UnsafeIISMethods.MgdRegisterEventSubscription(
                        appContext,
                        HttpApplication.IMPLICIT_HANDLER,
                        RequestNotification.ExecuteRequestHandler /*requestNotifications*/,
                        0 /*postRequestNotifications*/,
                        String.Empty /*type*/,
                        HttpApplication.MANAGED_PRECONDITION /*precondition*/,
                        new IntPtr(-1),
                        false /*useHighPriority*/);

                    if (hresult < 0)
                    {
                        throw new COMException(SR.GetString(SR.Failed_Pipeline_Subscription, HttpApplication.IMPLICIT_HANDLER),
                                               hresult);
                    }
                }

                if (app != null)
                {
                    HttpApplicationFactory.RecyclePipelineApplicationInstance(app);
                }
            }
        }