/// <summary> /// Resolves path relative to the current executing page /// </summary> public static string ResolvePath(string virtualPath) { if (String.IsNullOrEmpty(virtualPath)) { return virtualPath; } if (HttpContext.Current == null) { return virtualPath; } var httpContext = new HttpContextWrapper(HttpContext.Current); return ResolvePath(TemplateStack.GetCurrentTemplate(httpContext), httpContext, virtualPath); }
protected override void Execute(System.Web.Routing.RequestContext ctx) { var c2 = new HttpContextWrapper(ctx.HttpContext); if (RequireBasicAuth && String.IsNullOrEmpty(c2.Headers["Authorization"])) { var res = ctx.HttpContext.Response; res.StatusCode = 401; res.AddHeader("WWW-Authenticate", "Basic realm=\"CogMonSys\""); res.End(); return; } string auth = c2.Headers["Authorization"]; if (!string.IsNullOrEmpty(auth)) { } string sname = c2.Url.Segments[c2.Url.Segments.Length - 1]; if (sname.IndexOf('.') > 0) sname = sname.Substring(0, sname.IndexOf('.')); c2.UrlVariables = new Dictionary<string, string>(); c2.UrlVariables["name"] = sname; try { RequestContext.CurrentRequest = c2; CallHandler.HandleRequest(c2); } catch (Exception ex) { log.Warn("Error handling request {0}: {1}", c2.Url, ex); c2.ClearResponse(); c2.ResponseStatus = 500; c2.Output.WriteLine("Error: {0}", ex.Message); } finally { RequestContext.CurrentRequest = null; } }
public void GenerateClientUrl_ResolvesVirtualPath_WithApplicationPath() { AppDomainUtils.RunInSeparateAppDomain(() => { using (IDisposable _ = Utils.CreateHttpContext("default.aspx", "http://localhost/WebSite1/default.aspx"), __ = Utils.CreateHttpRuntime("/WebSite1/")) { // Arrange var vpath = "~/default.aspx"; var href = "~/world/test.aspx"; var expected = "/WebSite1/world/test.aspx"; var context = new HttpContextWrapper(HttpContext.Current); var page = new MockPage() { VirtualPath = vpath, Context = context }; // Act var actual1 = UrlUtil.GenerateClientUrl(context, vpath, href); var actual2 = page.Href(href); // Assert Assert.Equal(expected, actual1); Assert.Equal(expected, actual2); } }); }
//#endif static HttpRequestContext CreateHttpRequestContext(HttpContext httpContext) { var instance = new HttpRequestContext(); var context = new HttpContextWrapper(httpContext); IDictionary<string, object> routeValues = EmptyRouteValues; RouteData routeData = RouteTable.Routes.GetRouteData(context); if (routeData != null) { instance.RouteData = routeData; routeValues = routeData.Values; RemoveOptionalRoutingParameters(routeValues); var valueProvider = new DefaultValueProviderFactory().GetValueProvider(context, routeValues); instance.ValueProvider = valueProvider; instance.ServiceRequest = CreateServiceRequest(routeValues, routeData, valueProvider); } else { instance.ValueProvider = new DefaultValueProviderFactory().GetValueProvider(context, routeValues); } instance.HttpContext = context; return instance; }
void Application_AcquireRequestState(object sender, EventArgs e) { if (User.Identity.IsAuthenticated) { var context = new HttpContextWrapper(Context); var token = Request.Cookies["token"]; var user = Tools.GetFullUser(User.Identity.Name); if (token != null && user != null) { var t = new TokenDateViewModel(); if (DynamicToken.token.ContainsKey(user.Username)) { t = DynamicToken.token[user.Username]; } if (!string.IsNullOrEmpty(t.token) && t.validationToken != null) { var tok = token.Value.ToString().Split('~'); if (tok.Length == 2) { if (t.token.Trim() != tok[0].ToString().Trim()) { UnitOfWork u = new UnitOfWork(); Logs log = new Logs() { UserId = user.ID, LogDate = DateTime.Now, Description = "ورود به حساب کابری با اکانت " + user.Username + " که از قبل فعال بوده است" }; u.Log.Insert(log); u.Log.Save(); FormsAuthentication.SignOut(); if (System.Configuration.ConfigurationManager.AppSettings["removeAllToken"] == "true") { var validTime = DateTime.Now; validTime.AddMinutes(Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["validTokenTime"].ToString())); TokenDateViewModel model = new TokenDateViewModel() { token = Guid.NewGuid().ToString(), validationToken = validTime }; DynamicToken.token[user.Username] = model; HttpCookie StudentCookies = new HttpCookie("token"); StudentCookies.Value = "temp~temp"; StudentCookies.Expires = DateTime.Now.AddMinutes((-1) * Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["validTokenTime"].ToString())); Response.Cookies.Add(StudentCookies); } if (!context.Request.IsAjaxRequest()) { Context.Response.Clear(); Response.Redirect("/?id=u"); } else { Response.Clear(); Response.Redirect("/temp"); } } if (t.validationToken <= DateTime.Now) { UnitOfWork u = new UnitOfWork(); Logs log = new Logs() { UserId = user.ID, LogDate = DateTime.Now, Description = "اتمام زمان مجاز استفاده از سشن برای کاربر " + user.Username }; u.Log.Insert(log); u.Log.Save(); FormsAuthentication.SignOut(); if (System.Configuration.ConfigurationManager.AppSettings["removeAllToken"] == "true") { var validTime = DateTime.Now; validTime.AddMinutes(Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["validTokenTime"].ToString())); TokenDateViewModel model = new TokenDateViewModel() { token = Guid.NewGuid().ToString(), validationToken = validTime }; DynamicToken.token[user.Username] = model; HttpCookie StudentCookies = new HttpCookie("token"); StudentCookies.Value = "temp~temp"; StudentCookies.Expires = DateTime.Now.AddMinutes((-1) * Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["validTokenTime"].ToString())); Response.Cookies.Add(StudentCookies); } if (!context.Request.IsAjaxRequest()) { Context.Response.Clear(); Response.Redirect("/?id=timeOut"); } else { Response.Clear(); Response.Redirect("/timeOut"); } } } else { HttpCookie StudentCookies = new HttpCookie("token"); StudentCookies.Value = DynamicToken.token[user.Username].token + "~" + DynamicToken.token[user.Username].validationToken.ToString(); StudentCookies.Expires = DynamicToken.token[user.Username].validationToken; Response.Cookies.Add(StudentCookies); } } else { UnitOfWork u = new UnitOfWork(); Logs log = new Logs() { UserId = user.ID, LogDate = DateTime.Now, Description = "خروج کاربر توسط سیستم به دلیل وجود دو کاربر هم زمان با نام کاربری " + user.Username }; u.Log.Insert(log); u.Log.Save(); FormsAuthentication.SignOut(); if (System.Configuration.ConfigurationManager.AppSettings["removeAllToken"] == "true") { var validTime = DateTime.Now; validTime.AddMinutes(Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["validTokenTime"].ToString())); TokenDateViewModel model = new TokenDateViewModel() { token = Guid.NewGuid().ToString(), validationToken = validTime }; DynamicToken.token[user.Username] = model; HttpCookie StudentCookies = new HttpCookie("token"); StudentCookies.Value = "temp~temp"; StudentCookies.Expires = DateTime.Now.AddMinutes((-1) * Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["validTokenTime"].ToString())); Response.Cookies.Add(StudentCookies); } if (!context.Request.IsAjaxRequest()) { Context.Response.Clear(); Response.Redirect("/?id=u"); } else { Response.Clear(); Response.Redirect("/temp"); } } } else { try { HttpCookie StudentCookies = new HttpCookie("token"); StudentCookies.Value = DynamicToken.token[user.Username].token + "~" + DynamicToken.token[user.Username].validationToken.ToString(); StudentCookies.Expires = DynamicToken.token[user.Username].validationToken; Response.Cookies.Add(StudentCookies); } catch (Exception) { } } } }
protected virtual void ProcessRequest(HttpContext httpContext) { HttpContextBase httpContextBase = new HttpContextWrapper(httpContext); this.ProcessRequest(httpContextBase); }
public override async Task ProcessRequestAsync(HttpContext context) { context.ThrowIfNull("context"); var contextWrapper = new HttpContextWrapper(context); var requestWrapper = new HttpRequestWrapper(context.Request); var responseWrapper = new HttpResponseWrapper(context.Response); ExceptionDispatchInfo exceptionDispatchInfo = null; try { foreach (IRequestValidator requestValidator in _requestValidators) { ValidateResult validateResult = await requestValidator.Validate(requestWrapper, responseWrapper); if (validateResult.ResultType == ValidateResultType.RequestValidated) { continue; } await ProcessResponseAsync(context, validateResult.Response, null); return; } IEnumerable <RouteMatchResult> routeMatchResults = _routes.Select(arg => new RouteMatchResult(arg, arg.MatchesRequest(requestWrapper))); IEnumerable <Task <ResponseResult> > responseResultTasks = _responseGenerators.Select(arg => arg.GetResponseAsync(contextWrapper, routeMatchResults)); foreach (Task <ResponseResult> responseResultTask in responseResultTasks) { ResponseResult responseResult = await responseResultTask; if (responseResult.ResultType != ResponseResultType.ResponseGenerated) { continue; } await ProcessResponseAsync(context, await responseResult.Response, responseResult.CacheKey); return; } } catch (Exception exception) { exceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception); } if (exceptionDispatchInfo != null) { foreach (IErrorHandler errorHandler in _errorHandlers) { if ((await errorHandler.HandleAsync(contextWrapper, exceptionDispatchInfo.SourceException)).ResultType != HandleResultType.Handled) { continue; } exceptionDispatchInfo = null; break; } } if (exceptionDispatchInfo != null) { exceptionDispatchInfo.Throw(); } }
protected void Application_Error(object sender, EventArgs e) { var httpContext = ((MvcApplication)sender).Context; var currentController = " "; var currentAction = " "; var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext)); if (currentRouteData != null) { if (currentRouteData.Values["controller"] != null && !string.IsNullOrEmpty(currentRouteData.Values["controller"].ToString())) { currentController = currentRouteData.Values["controller"].ToString(); } if (currentRouteData.Values["action"] != null && !string.IsNullOrEmpty(currentRouteData.Values["action"].ToString())) { currentAction = currentRouteData.Values["action"].ToString(); } } var ex = Server.GetLastError(); try { if (ex is HttpException) { if (((HttpException)ex).GetHttpCode() != 404) { EmailHelper.SendErrorEmail(ConfigurationManager.AppSettings["ErrorEmailAddress"], ex, currentController, currentAction); } } } catch (Exception exx) { // } var routeData = new RouteData(); var action = "GenericError"; if (ex is HttpException) { var httpEx = ex as HttpException; switch (httpEx.GetHttpCode()) { case 400: action = "BadRequest"; break; case 404: action = "NotFound"; break; // others if any } } httpContext.ClearError(); httpContext.Response.Clear(); httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500; httpContext.Response.TrySkipIisCustomErrors = true; routeData.Values["controller"] = "Error"; routeData.Values["action"] = action; routeData.Values["exception"] = new HandleErrorInfo(ex, currentController, currentAction); IController errorController = new ErrorController(); HttpContextWrapper wrapper = new HttpContextWrapper(httpContext); var rc = new RequestContext(wrapper, routeData); errorController.Execute(rc); }
public DataForRegularStudentDTO GetDataForRegularStudent(string embg) { if (string.IsNullOrEmpty(embg)) { throw new ArgumentException("Невалиден ЕМБГ, внесениот ЕМБГ треба да содржи 13 цифри. ", embg); } if (embg.Any(x => (char.IsLetter(x) || char.IsSeparator(x) || char.IsPunctuation(x) || char.IsSymbol(x)))) { throw new ArgumentException("Невалиден ЕМБГ, внесениот ЕМБГ содржи карактери/симболи:", embg); } var embgTemp = new String(embg.Where(Char.IsDigit).ToArray()); if (embgTemp.Length != 13) { throw new ArgumentException("Невалиден ЕМБГ:", embg); } _logger.Info("start GetDataForRegularStudent"); //var monClient = new DRegStudentClient(); var studentDto = new DataForRegularStudentDTO(); var student = ""; try { _logger.Info("MONClient"); var production = ConfigurationManager.AppSettings["Enviroment"]; if (production == "Production") { //New corrected adapter var monClient = new MONPotvrdaZaRedovenUcenik.DRegStudentClient(); using (OperationContextScope scope = new OperationContextScope(monClient.InnerChannel)) { var httpRequestProperty = new HttpRequestMessageProperty(); httpRequestProperty.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(monClient.ClientCredentials.UserName.UserName + ":" + monClient.ClientCredentials.UserName.Password)); httpRequestProperty.Headers.Add("NekakovKod", "kodot"); OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty; student = monClient.GetStuD(embg); //dzgrObject = MONClient.GetPropertyList(username, password, municipality, cadastralMunicipality, noPropertyList); //PaymentResponse = AKNClient.Payment(PaymentRequest); } } else { //New corrected adapter var monClient = new MONPotvrdaZaRedovenUcenikTest.DRegStudentClient(); using (OperationContextScope scope = new OperationContextScope(monClient.InnerChannel)) { var httpRequestProperty = new HttpRequestMessageProperty(); httpRequestProperty.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(monClient.ClientCredentials.UserName.UserName + ":" + monClient.ClientCredentials.UserName.Password)); httpRequestProperty.Headers.Add("NekakovKod", "kodot"); OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty; student = monClient.GetStuD(embg); //dzgrObject = MONClient.GetPropertyList(username, password, municipality, cadastralMunicipality, noPropertyList); //PaymentResponse = AKNClient.Payment(PaymentRequest); } } //var student = MONClient.GetStuD(embg); if (student != null) { _logger.Info(student); var stringReader = new StringReader(student); var serializer = new XmlSerializer(typeof(DataForRegularStudentDTO)); try { studentDto = (DataForRegularStudentDTO)serializer.Deserialize(stringReader); var context = HttpContext.Current; var contextBase = new HttpContextWrapper(context); var routeData = new RouteData(); routeData.Values.Add("controller", "Template"); var controllerContext = new ControllerContext(contextBase, routeData, new MONController.EmptyController()); studentDto.FillBasicPrintInfo("Податоци за редовен ученик", InstitutionName); var r = new Rotativa.ViewAsPdf("PrintDataForRegularStudent", studentDto); var binary = r.BuildPdf(controllerContext); var date = DateTime.Now.Day; var month = DateTime.Now.Month; var year = DateTime.Now.Year; var hour = DateTime.Now.Hour; var minutes = DateTime.Now.Minute; var secods = DateTime.Now.Second; var namepdf = "MON_GetDataForStudent_" + secods + "_" + minutes + "_" + hour + "_" + date + "_" + month + "_" + year + ".pdf"; var namexml = "MON_GetDataForStudent_" + secods + "_" + minutes + "_" + hour + "_" + date + "_" + month + "_" + year + ".xml"; var path = WebConfigurationManager.AppSettings["PathToFile"]; studentDto.FilePdfName = namepdf; studentDto.FileXMLName = namexml; var pathpdf = path + namepdf; File.WriteAllBytes(pathpdf, binary); var pathxml = path + namexml; File.WriteAllText(pathxml, student); } catch { var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(student); var mes = xmlDoc.GetElementsByTagName("message")[0].InnerText; studentDto.Message = mes; } } } //catch (FaultException<MONPotvrdaZaRedovenUcenikTest.InteropFault> ex) //{ // _logger.Error(ex.Message, "MON - GetDataForRegularStudent() - Custom fault error."); // throw ex; //} catch (FaultException ex) { _logger.Error(ex.Message, "MON - GetDataForRegularStudent() - Fault exception error."); throw ex; } catch (Exception ex) { _logger.Error(ex.Message, "MON - GetDataForRegularStudent() - Exception error."); throw ex; } return(studentDto); }
public HttpResponseMessage YourActionName() { var request = new HttpContextWrapper(CurrentContext).Request;
protected virtual void ProcessRequest(HttpContext httpContext) { HttpContextBase httpContextBase = new HttpContextWrapper(httpContext); ProcessRequest(httpContextBase); }
/// <summary> /// Gets the request context. /// </summary> /// <returns></returns> private static RequestContext GetRequestContext() { HttpContextBase context = new HttpContextWrapper(HttpContext.Current); return(new RequestContext(context, RouteTable.Routes.GetRouteData(context))); }
/// <summary> /// Processes the image. /// </summary> /// <param name="context"> /// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides /// references to the intrinsic server objects /// </param> /// <returns> /// The <see cref="T:System.Threading.Tasks.Task"/>. /// </returns> private async Task ProcessImageAsync(HttpContext context) { HttpRequest request = context.Request; string rawUrl = this.GetRequestUrl(request); // Should we ignore this request? if (string.IsNullOrWhiteSpace(rawUrl) || rawUrl.ToUpperInvariant().Contains("IPIGNORE=TRUE")) { return; } // Sometimes the request is url encoded // See https://github.com/JimBobSquarePants/ImageProcessor/issues/478 // This causes a bit of a nightmare as the incoming request is corrupted and cannot be used for splitting // out each url part. This becomes a manual job. string url = rawUrl; string applicationPath = request.ApplicationPath; IImageService currentService = this.GetImageServiceForRequest(url, applicationPath); if (currentService != null) { // Parse url string requestPath, queryString; UrlParser.ParseUrl(url, currentService.Prefix, out requestPath, out queryString); // Map the request path if file local. bool isFileLocal = currentService.IsFileLocalService; if (currentService.IsFileLocalService) { requestPath = HostingEnvironment.MapPath(requestPath); } if (string.IsNullOrWhiteSpace(requestPath)) { return; } // Parse any protocol values from settings if no protocol is present. if (currentService.Settings.ContainsKey("Protocol") && (ProtocolRegex.Matches(requestPath).Count == 0 || ProtocolRegex.Matches(requestPath)[0].Index > 0)) { // ReSharper disable once PossibleNullReferenceException requestPath = currentService.Settings["Protocol"] + "://" + requestPath.TrimStart('/'); } // Replace any presets in the querystring with the actual value. queryString = this.ReplacePresetsInQueryString(queryString); HttpContextWrapper httpContextBase = new HttpContextWrapper(context); // Execute the handler which can change the querystring // LEGACY: #pragma warning disable 618 queryString = this.CheckQuerystringHandler(context, queryString, rawUrl); #pragma warning restore 618 // NEW WAY: ValidatingRequestEventArgs validatingArgs = new ValidatingRequestEventArgs(httpContextBase, queryString); this.OnValidatingRequest(validatingArgs); // If the validation has failed based on events, return if (validatingArgs.Cancel) { ImageProcessorBootstrapper.Instance.Logger.Log <ImageProcessingModule>("Image processing has been cancelled by an event"); return; } // Re-assign based on event handlers queryString = validatingArgs.QueryString; // Break out if we don't meet critera. bool interceptAll = interceptAllRequests != null && interceptAllRequests.Value; if (string.IsNullOrWhiteSpace(requestPath) || (!interceptAll && string.IsNullOrWhiteSpace(queryString))) { return; } // Check whether the path is valid for other requests. // We've already checked the unprefixed requests in GetImageServiceForRequest(). if (!string.IsNullOrWhiteSpace(currentService.Prefix) && !currentService.IsValidRequest(requestPath)) { return; } using (await Locker.LockAsync(rawUrl)) { // Create a new cache to help process and cache the request. this.imageCache = (IImageCache)ImageProcessorConfiguration.Instance .ImageCache.GetInstance(requestPath, url, queryString); // Is the file new or updated? bool isNewOrUpdated = await this.imageCache.IsNewOrUpdatedAsync(); string cachedPath = this.imageCache.CachedPath; // Only process if the file has been updated. if (isNewOrUpdated) { byte[] imageBuffer = null; string mimeType; try { imageBuffer = await currentService.GetImage(requestPath); } catch (HttpException ex) { // We want 404's to be handled by IIS so that other handlers/modules can still run. if (ex.GetHttpCode() == (int)HttpStatusCode.NotFound) { ImageProcessorBootstrapper.Instance.Logger.Log <ImageProcessingModule>(ex.Message); return; } } if (imageBuffer == null) { return; } // Using recyclable streams here should dramatically reduce the overhead required using (MemoryStream inStream = MemoryStreamPool.Shared.GetStream("inStream", imageBuffer, 0, imageBuffer.Length)) { // Process the Image. Use a recyclable stream here to reduce the allocations MemoryStream outStream = MemoryStreamPool.Shared.GetStream(); if (!string.IsNullOrWhiteSpace(queryString)) { // Animation is not a processor but can be a specific request so we should allow it. bool processAnimation; AnimationProcessMode mode = this.ParseAnimationMode(queryString, out processAnimation); // Attempt to match querystring and processors. IWebGraphicsProcessor[] processors = ImageFactoryExtensions.GetMatchingProcessors(queryString); if (processors.Any() || processAnimation) { // Process the image. bool exif = preserveExifMetaData != null && preserveExifMetaData.Value; bool gamma = fixGamma != null && fixGamma.Value; using (ImageFactory imageFactory = new ImageFactory(exif, gamma) { AnimationProcessMode = mode }) { imageFactory.Load(inStream).AutoProcess(processors).Save(outStream); mimeType = imageFactory.CurrentImageFormat.MimeType; } } else if (this.ParseCacheBuster(queryString)) { // We're cachebustng. Allow the value to be cached await inStream.CopyToAsync(outStream); mimeType = FormatUtilities.GetFormat(outStream).MimeType; } else { // No match? Someone is either attacking the server or hasn't read the instructions. // Either way throw an exception to prevent caching. string message = $"The request {request.Unvalidated.RawUrl} could not be understood by the server due to malformed syntax."; ImageProcessorBootstrapper.Instance.Logger.Log <ImageProcessingModule>(message); throw new HttpException((int)HttpStatusCode.BadRequest, message); } } else { // We're capturing all requests. await inStream.CopyToAsync(outStream); mimeType = FormatUtilities.GetFormat(outStream).MimeType; } // Fire the post processing event. EventHandler <PostProcessingEventArgs> handler = OnPostProcessing; if (handler != null) { string extension = Path.GetExtension(cachedPath); PostProcessingEventArgs args = new PostProcessingEventArgs { Context = context, ImageStream = outStream, ImageExtension = extension }; handler(this, args); outStream = args.ImageStream; } // Add to the cache. await this.imageCache.AddImageToCacheAsync(outStream, mimeType); // Cleanup outStream.Dispose(); } // Store the response type and cache dependency in the context for later retrieval. context.Items[CachedResponseTypeKey] = mimeType; bool isFileCached = new Uri(cachedPath).IsFile; if (isFileLocal) { if (isFileCached) { // Some services might only provide filename so we can't monitor for the browser. context.Items[CachedResponseFileDependency] = Path.GetFileName(requestPath) == requestPath ? new[] { cachedPath } : new[] { requestPath, cachedPath }; } else { context.Items[CachedResponseFileDependency] = Path.GetFileName(requestPath) == requestPath ? null : new[] { requestPath }; } } else if (isFileCached) { context.Items[CachedResponseFileDependency] = new[] { cachedPath }; } } // The cached file is valid so just rewrite the path. this.imageCache.RewritePath(context); // Redirect if not a locally store file. if (!new Uri(cachedPath).IsFile) { context.ApplicationInstance.CompleteRequest(); } // Trim the cache. await this.imageCache.TrimCacheAsync(); } } }
private static string ResolveCanvasUrl(string resolvedUrl, HttpContextWrapper httpContext) { return(GetCanvasUrlBuilder(httpContext).BuildCanvasUrl(resolvedUrl).AbsoluteUri); }
/// <summary> /// Gets the name of the OAuth povider. /// </summary> /// <returns></returns> public string GetOAuthPoviderName() { var context = new HttpContextWrapper(HttpContext.Current); return(OpenAuthSecurityManager.GetProviderName(context)); }
public static void Handle(HttpContext context) { int statusCode = 500; var exception = context.Server.GetLastError(); var httpException = exception as HttpException; var routeData = new RouteData(); routeData.Values.Add("controller", "Error"); if (httpException == null) { routeData.Values.Add("action", "Index"); } else //It's an HttpException, Let's handle it. { statusCode = httpException.GetHttpCode(); switch (statusCode) { case 401: // Unauthorized case 405: // Method Not Allowed break; case 403: // Forbidden routeData.Values.Add("action", "Error403"); break; case 404: // Page not found. routeData.Values.Add("action", "Error404"); break; case 500: // Server error. routeData.Values.Add("action", "Error500"); break; } } try { // Avoid IIS7 getting in the middle context.Response.TrySkipIisCustomErrors = true; context.Response.StatusCode = statusCode; } catch (HttpException) { // Catch exception that says: // Server cannot set status after HTTP headers have been sent. return; } context.Response.Clear(); // Pass exception details to the target error View. routeData.Values.Add("exception", exception); // Clear the error on server. context.Server.ClearError(); var contextWrapper = new HttpContextWrapper(context); var requestContext = new RequestContext(contextWrapper, routeData); var controller = DependencyResolver.Current.GetService <ErrorController>(); // Call target Controller and pass the routeData. IController errorController = controller; errorController.Execute(requestContext); }
/// <summary> /// Processes the request, evaluating it for the need to redirect based on configured settings. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void ProcessRequest(object sender, EventArgs e) { // Cast the source as an HttpApplication instance. var application = sender as HttpApplication; if (application == null) { Logger.Log("No HttpApplication supplied.", Logger.LogLevel.Warn); return; } // Wrap the application's context (for testability) and process the request. var context = new HttpContextWrapper(application.Context); _requestProcessor.Process(context, EvaluatorCallback); }
protected virtual IAsyncResult BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, object state) { HttpContextBase httpContextBase = new HttpContextWrapper(httpContext); return(BeginProcessRequest(httpContextBase, callback, state)); }
/// <summary> /// 链接地址 /// </summary> /// <param name="htmlHelper"></param> /// <param name="linkText"></param> /// <param name="actionName"></param> /// <param name="controllerName"></param> /// <param name="routeValues"></param> /// <param name="htmlAttributes"></param> /// <param name="requireAbsoluteUrl"></param> /// <returns></returns> public static string ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes, bool requireAbsoluteUrl) { if (requireAbsoluteUrl) { HttpContextBase currentContext = new HttpContextWrapper(HttpContext.Current); var routeData = RouteTable.Routes.GetRouteData(currentContext); routeData.Values["controller"] = controllerName; routeData.Values["action"] = actionName; var domainRoute = routeData.Route as DomainRoute; if (domainRoute != null) { var domainData = domainRoute.GetDomainData(new RequestContext(currentContext, routeData), routeData.Values); return htmlHelper.ActionLink(linkText, actionName, controllerName, domainData.Protocol, domainData.HostName, domainData.Fragment, routeData.Values, null) .ToHtmlString(); } } return htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes).ToHtmlString(); }
public void GenerateOAuthCallbackUrlTest() { #if NET45 Func <string, string, string, HttpContextBase> getHttpContextBase = (url, queryString, baseUrl) => { var context = new Mock <HttpContextBase>(); var request = new Mock <HttpRequestBase>(); var response = new Mock <HttpResponseBase>(); request.Setup(r => r.Url).Returns(new Uri(url)); request.Setup(r => r.ApplicationPath).Returns(baseUrl); context.Setup(c => c.Request).Returns(request.Object); context.Setup(c => c.Response).Returns(response.Object); context.Setup(c => c.Response).Returns(response.Object); return(context.Object); var httpContext = new HttpContext(new HttpRequest("Senparc", url, queryString), new HttpResponse(null)); var httpContextBase = new HttpContextWrapper(httpContext); return(httpContextBase); }; #else Func <string, string, string, HttpContext> getHttpContextBase = (url, queryString, baseUrl) => { var uri = new Uri(url); var scheme = uri.Scheme; var path = uri.LocalPath; var httpContext = new DefaultHttpContext(); httpContext.Request.Path = path; httpContext.Request.Host = new HostString(uri.Host, uri.Port); httpContext.Request.Scheme = scheme; httpContext.Request.QueryString = new QueryString(uri.Query); httpContext.Request.PathBase = baseUrl; return(httpContext); }; #endif string virtualPath = null;//虚拟路径 { var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com/Home/Index", "", virtualPath); var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback"); Console.WriteLine("\r\n普通 HTTP Url:" + callbackUrl); Assert.AreEqual( "https://sdk.weixin.senparc.com/TenpayV3/OAuthCallback?returnUrl=http%3a%2f%2fsdk.weixin.senparc.com%2fHome%2fIndex", callbackUrl, true); } { var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1", virtualPath); var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback"); Console.WriteLine("\r\n带参数 HTTP Url:" + callbackUrl); Assert.AreEqual( "https://sdk.weixin.senparc.com/TenpayV3/OAuthCallback?returnUrl=http%3a%2f%2fsdk.weixin.senparc.com%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1", callbackUrl, true); } { var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com:8080/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1", virtualPath); var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback"); Console.WriteLine("\r\n带参数、带端口 HTTP Url:" + callbackUrl); Assert.AreEqual( "https://sdk.weixin.senparc.com:8080/TenpayV3/OAuthCallback?returnUrl=http%3a%2f%2fsdk.weixin.senparc.com%3a8080%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1", callbackUrl, true); } { var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com/Home/Index", "", virtualPath); var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback"); Console.WriteLine("\r\n普通 HTTPS Url:" + callbackUrl); Assert.AreEqual( "https://sdk.weixin.senparc.com/TenpayV3/OAuthCallback?returnUrl=https%3a%2f%2fsdk.weixin.senparc.com%2fHome%2fIndex", callbackUrl, true); } { var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1", virtualPath); var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback"); Console.WriteLine("\r\n带参数 HTTPS Url:" + callbackUrl); Assert.AreEqual( "https://sdk.weixin.senparc.com/TenpayV3/OAuthCallback?returnUrl=https%3a%2f%2fsdk.weixin.senparc.com%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1", callbackUrl, true); } { var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com:1433/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1", virtualPath); var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback"); Console.WriteLine("\r\n带参数、带端口 HTTPS Url:" + callbackUrl); Assert.AreEqual( "https://sdk.weixin.senparc.com:1433/TenpayV3/OAuthCallback?returnUrl=https%3a%2f%2fsdk.weixin.senparc.com%3a1433%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1", callbackUrl, true); } //虚拟路径 { virtualPath = "/VirtualPath"; var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com:1433/VirtualPath/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1", virtualPath); //Console.WriteLine("\r\nhttpContext.Request.AbsoluteUri():"+httpContext.Request.AbsoluteUri()); var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback"); Console.WriteLine("\r\n带参数、带端口 HTTPS Url:" + callbackUrl); #if NET35 || NET40 || NET45 var expectedUrl = "https://sdk.weixin.senparc.com:1433/VirtualPath/TenpayV3/OAuthCallback?returnUrl=https%3a%2f%2fsdk.weixin.senparc.com%3a1433%2fVirtualPath%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1"; #else //.NET Standard(.NET Core)下因为模拟会存在偏差(无法自动识别Url中的VirtualPath为特殊的虚拟目录,所以会出现重复),因此以下结果是可以接受的 var expectedUrl = "https://sdk.weixin.senparc.com:1433/VirtualPath/TenpayV3/OAuthCallback?returnUrl=https%3a%2f%2fsdk.weixin.senparc.com%3a1433%2fVirtualPath%2fVirtualPath%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1"; #endif Assert.AreEqual(expectedUrl, callbackUrl, true); } }
internal void ProcessRequestInternal(HttpContext context) { // enable dynamic validation for this request ValidationUtility.EnableDynamicValidation(context); context.Request.ValidateInput(); HttpContextBase contextBase = new HttpContextWrapper(context); ProcessRequestInternal(contextBase); }
public StackdriverExceptionHandler(IContextExceptionLogger logger, IHttpContextAccessor httpContextAccessor) { this.logger = logger; httpContextWrapper = new HttpContextWrapper(httpContextAccessor); }
/// <summary> /// Catchall handler when errors are thrown outside the MVC pipeline /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Application_Error(object sender, EventArgs e) { var ex = Server.GetLastError(); var contextBase = new HttpContextWrapper(Context); try { if ((ex as HttpException).GetHttpCode() == 404) { var s = "~/Home/Redir" + contextBase.Request.FilePath; contextBase.RewritePath(s, false); contextBase.Server.TransferRequest(s); } } catch {} if (Context.Items["ErrorID"] != null) { return; //this one has already been handled in one of the MVC error filters } if (ex.InnerException != null) { ex = ex.InnerException; } Server.ClearError(); if (ex == null) { return; } var code = (ex is HttpException) ? (ex as HttpException).GetHttpCode() : 500; var bAjax = IsAjaxRequest(); var sMessage = (bAjax) ? "AJAX call error" : ""; var eid = Logging.WriteDebugInfoToErrorLog(sMessage, ex); Context.Items.Add("ErrorID", eid); //to keep us from doing this again in the same call Response.Clear(); if (bAjax) { //this is a json call; tryskip will return our IDs in response.write, 500 will throw in jquery Response.TrySkipIisCustomErrors = true; Response.StatusCode = 500; Response.StatusDescription = String.Format("{0} Application Error", Utils.ApplicationName); Response.ContentType = "application/json"; Response.Write(JsonConvert.SerializeObject(new ErrResponsePoco { DbErrorId = eid })); Response.End(); } else { try { SiteUtils.ReturnViaCode(contextBase, code); } // ReSharper disable once EmptyGeneralCatchClause catch (Exception) { } } }
protected void Application_BeginRequest(object sender, EventArgs e) { var context = new HttpContextWrapper(HttpContext.Current); SecurityManager.PutOnCorrectTenant(context); }
private void HandleRequest(object sender, EventArgs e) { var context = new HttpContextWrapper(((HttpApplication)sender).Context); FilterAndProcessRequest(context, context.ApplicationInstance.CompleteRequest); }
public static string GetSiteUrl(this HttpContext context) { HttpContextWrapper wrapper = new HttpContextWrapper(context); return(GetSiteUrl(wrapper as HttpContextBase, true)); }
public void GenerateOAuthCallbackUrlTest() { #if NET45 Func <string, string, HttpContextBase> getHttpContextBase = (url, queryString) => { var httpContext = new HttpContext(new HttpRequest("Senparc", url, queryString), new HttpResponse(null)); var httpContextBase = new HttpContextWrapper(httpContext); return(httpContextBase); }; #else Func <string, string, HttpContext> getHttpContextBase = (url, queryString) => { var uri = new Uri(url); var scheme = uri.Scheme; var path = uri.LocalPath; var httpContext = new DefaultHttpContext(); httpContext.Request.Path = path; httpContext.Request.Host = new HostString(uri.Host, uri.Port); httpContext.Request.Scheme = scheme; httpContext.Request.QueryString = new QueryString(uri.Query); return(httpContext); }; #endif { var httpContext = getHttpContextBase("http://sdk.weixin.senparc.com/Home/Index", ""); var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback"); Console.WriteLine("普通 HTTP Url:" + callbackUrl); Assert.AreEqual( "http://sdk.weixin.senparc.com/TenpayV3/OAuthCallback?returnUrl=http%3a%2f%2fsdk.weixin.senparc.com%2fHome%2fIndex", callbackUrl, true); } { var httpContext = getHttpContextBase("http://sdk.weixin.senparc.com/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1"); var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback"); Console.WriteLine("带参数 HTTP Url:" + callbackUrl); Assert.AreEqual( "http://sdk.weixin.senparc.com/TenpayV3/OAuthCallback?returnUrl=http%3a%2f%2fsdk.weixin.senparc.com%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1", callbackUrl, true); } { var httpContext = getHttpContextBase("http://sdk.weixin.senparc.com:8080/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1"); var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback"); Console.WriteLine("带参数、带端口 HTTP Url:" + callbackUrl); Assert.AreEqual( "http://sdk.weixin.senparc.com:8080/TenpayV3/OAuthCallback?returnUrl=http%3a%2f%2fsdk.weixin.senparc.com%3a8080%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1", callbackUrl, true); } { var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com/Home/Index", ""); var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback"); Console.WriteLine("普通 HTTPS Url:" + callbackUrl); Assert.AreEqual( "https://sdk.weixin.senparc.com/TenpayV3/OAuthCallback?returnUrl=https%3a%2f%2fsdk.weixin.senparc.com%2fHome%2fIndex", callbackUrl, true); } { var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1"); var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback"); Console.WriteLine("带参数 HTTPS Url:" + callbackUrl); Assert.AreEqual( "https://sdk.weixin.senparc.com/TenpayV3/OAuthCallback?returnUrl=https%3a%2f%2fsdk.weixin.senparc.com%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1", callbackUrl, true); } { var httpContext = getHttpContextBase("https://sdk.weixin.senparc.com:1433/Home/Index?a=1&b=2&c=3-1", "a=1&b=2&c=3-1"); var callbackUrl = UrlUtility.GenerateOAuthCallbackUrl(httpContext, "/TenpayV3/OAuthCallback"); Console.WriteLine("带参数、带端口 HTTPS Url:" + callbackUrl); Assert.AreEqual( "https://sdk.weixin.senparc.com:1433/TenpayV3/OAuthCallback?returnUrl=https%3a%2f%2fsdk.weixin.senparc.com%3a1433%2fHome%2fIndex%3fa%3d1%26b%3d2%26c%3d3-1", callbackUrl, true); } }
public object GetData(HttpApplication application) { var result = new List <object[]> { new[] { "Match", "Area", "Url", "Data", "Constraints", "DataTokens" } }; var hasEverMatched = false; using (RouteTable.Routes.GetReadLock()) { var httpContext = new HttpContextWrapper(HttpContext.Current); foreach (RouteBase routeBase in RouteTable.Routes) { var routeData = routeBase.GetRouteData(httpContext); bool matchesCurrentRequest = (routeData != null); var route = routeBase as Route; if (route != null) { RouteValueDictionary values = null; if (routeData != null) { values = routeData.Values; } var data = new List <object[]> { new [] { "Placeholder", "Default Value", "Actual Value" } }; if (values != null && route.Defaults != null) { foreach (var item in route.Defaults) { var @default = item.Value == UrlParameter.Optional ? "_Optional_" : item.Value; var value = values[item.Key]; if (value != null) { value = value == UrlParameter.Optional ? "_Optional_" : value; } data.Add(new [] { item.Key, @default, value }); } } var area = "_Root_"; if (route.DataTokens != null && route.DataTokens.ContainsKey("area")) { area = route.DataTokens["area"].ToString(); } result.Add(new object[] { matchesCurrentRequest.ToString(), area, route.Url, data.Count > 1 ? data : null, (route.Constraints == null || route.Constraints.Count == 0) ? null : route.Constraints, (route.DataTokens == null || route.DataTokens.Count == 0) ? null : route.DataTokens, matchesCurrentRequest && !hasEverMatched ? "selected" : "" }); } else { result.Add(new object[] { matchesCurrentRequest.ToString(), null, null, null, null }); } hasEverMatched = hasEverMatched || matchesCurrentRequest; } } return(result); }
protected void Page_Load(object sender, EventArgs e) { //prevent caching of reports - fixes issues of 'reports execution has expired or cannot be found' error this.Response.CacheControl = "no-cache"; // Ensure SSRSQueryParameter exist if (_sessionManager.SSRSQueryParameter == null) { _sessionManager.SSRSQueryParameter = new List <string> { "", "", "", "" }; } // Add to session user Query from SSRS/RDL if (this.OperationalReportViewer != null && this.OperationalReportViewer.ServerReport != null && this.OperationalReportViewer.ServerReport.ReportServerCredentials != null) { // Query parameter assumed to be 3rd paramter ReportParameterInfoCollection reportParm = this.OperationalReportViewer.ServerReport.GetParameters(); if (reportParm.Count() > 2 && reportParm.ToList <ReportParameterInfo>()[2].Values.Count() > 0) { switch (reportParm.ToList <ReportParameterInfo>()[2].Name) { case "LastName": _sessionManager.SSRSQueryParameter[QUERY_LASTNAME] = reportParm.ToList <ReportParameterInfo>()[2].Values[0].ToString(); break; case "NINO": _sessionManager.SSRSQueryParameter[QUERY_NINO] = reportParm.ToList <ReportParameterInfo>()[2].Values[0].ToString(); break; case "Postcode": _sessionManager.SSRSQueryParameter[QUERY_POSTCODE] = reportParm.ToList <ReportParameterInfo>()[2].Values[0].ToString(); break; case "IncidentID": _sessionManager.SSRSQueryParameter[QUERY_INCIDENTID] = reportParm.ToList <ReportParameterInfo>()[2].Values[0].ToString(); break; default: break; } } } if (!Page.IsPostBack) { AuthorisationManager authManager = new AuthorisationManager(); authManager.GetUserAuthorisationInfo(new HttpContextWrapper(HttpContext.Current), "UCB"); // Check authorised user var httpContextBase = new HttpContextWrapper(HttpContext.Current); if (!httpContextBase.User.IsInRole(AppRoles.APPLICATION)) { Response.Redirect("~/Home/UnAuthorized"); } if (!string.IsNullOrEmpty(_sessionManager.MessageFromPageFrom)) { this.Message.InnerText = _sessionManager.MessageFromPageFrom; _sessionManager.MessageFromPageFrom = null; } else { this.Message.InnerText = ""; } // Get report server and location information string reportpath; string ReportServer = ConfigurationManager.AppSettings["ReportServer"]; string ReportLocation = ConfigurationManager.AppSettings["ReportLocation"]; ScriptManager MyScriptManager = ScriptManager.GetCurrent(this); MyScriptManager.AsyncPostBackTimeout = 600; this.OperationalReportViewer.ServerReport.ReportServerUrl = new Uri(ReportServer); this.OperationalReportViewer.ServerReport.ReportServerCredentials = new ReportCredentials(); this.OperationalReportViewer.InteractiveDeviceInfos.Add("AccessibleTablix", "true"); if (_sessionManager.PageFrom != "MIMenu") { reportpath = ConfigurationManager.AppSettings["ReportLocation"] + _sessionManager.IsExpected(_sessionManager.RequestedReport);//.Request.QueryString.Get("report"); switch (_sessionManager.IsExpected(_sessionManager.RequestedReport)) { case "MyForwardLookReport": case "MyNewReportsReport": case "MyReviewsReport": case "SPLByAllCases": case "SPLByArchived": case "SPLByBusinessUnit": case "SPLByControlMeasure": case "SPLByDistrict": case "SPLByName": case "SPLByNino": case "SPLByPostcode": case "SPLByIncidentID": case "SPLBy3rdPartyReferrals": case "SPLBySite": this.OperationalReportViewer.ShowPrintButton = false; this.OperationalReportViewer.ShowExportControls = false; break; default: this.OperationalReportViewer.ShowPrintButton = true; this.OperationalReportViewer.ShowExportControls = true; break; } } else { reportpath = ConfigurationManager.AppSettings["PublishedLocation"] + _sessionManager.RequestedReport; StandardReportModel Report = _sessionManager.CurrentStandardReport; if (Report != null) { if (Report.IsPrintable) { this.OperationalReportViewer.ShowPrintButton = true; } else { this.OperationalReportViewer.ShowPrintButton = false; } if (Report.IsExportable) { this.OperationalReportViewer.ShowExportControls = true; } else { this.OperationalReportViewer.ShowExportControls = false; } reportpath = ConfigurationManager.AppSettings["PublishedLocation"] + Report.ReportName; } } this.OperationalReportViewer.ServerReport.ReportPath = reportpath; try { /* * //Need to pass these * SessionManager.UserIdentity; * then call stored proc in report (have as Look in repositories for further info) * (Guid,Guid,"AccuracyMonitoring",string.Empty) (ConfigurationAllowDefinition NetPipeStyleUriParser */ int startOfBaseUrl = HttpContext.Current.Request.Url.ToString().IndexOf("/Reports/Reports.aspx"); string baseUrl = HttpContext.Current.Request.Url.ToString().Substring(0, startOfBaseUrl); List <ReportParameter> ParameterList = new List <ReportParameter>(); if (_sessionManager.PageFrom != "MIMenu") { ParameterList.Add(new ReportParameter("BaseUrl", baseUrl)); ParameterList.Add(new ReportParameter("UserID", _sessionManager.UserID)); // Add Query from session, which was saved when RDL executed switch (_sessionManager.IsExpected(_sessionManager.RequestedReport)) { case "SPLByName": ParameterList.Add(new ReportParameter("LastName", _sessionManager.SSRSQueryParameter[QUERY_LASTNAME])); break; case "SPLByNino": ParameterList.Add(new ReportParameter("NINO", _sessionManager.SSRSQueryParameter[QUERY_NINO])); break; case "SPLByPostcode": ParameterList.Add(new ReportParameter("Postcode", _sessionManager.SSRSQueryParameter[QUERY_POSTCODE])); break; case "SPLByIncidentID": ParameterList.Add(new ReportParameter("IncidentID", _sessionManager.SSRSQueryParameter[QUERY_INCIDENTID])); break; default: break; } } else { ParameterList.Add(new ReportParameter("ReportUserName", _sessionManager.UserName)); ParameterList.Add(new ReportParameter("ReportUserCode", _sessionManager.UserID)); } this.OperationalReportViewer.ShowParameterPrompts = true; this.OperationalReportViewer.ShowPromptAreaButton = true; this.OperationalReportViewer.PromptAreaCollapsed = false; this.OperationalReportViewer.ServerReport.SetParameters(ParameterList); } catch { //If ReportUser parameter doesn't exist ignore it. } } }
private void OnPostResolveRequestCache(object sender, EventArgs e) { HttpContextBase context = new HttpContextWrapper(((HttpApplication)sender).Context); PostResolveRequestCache(context); }
void IHttpHandler.ProcessRequest(HttpContext context) { var contextBase = new HttpContextWrapper(context); ClientDependencyType type; string fileKey; int version = 0; if (string.IsNullOrEmpty(context.Request.PathInfo)) { var decodedUrl = HttpUtility.HtmlDecode(context.Request.Url.OriginalString); var query = decodedUrl.Split(new char[] { '?' }); if (query.Length < 2) { throw new ArgumentException("No query string found in request"); } var queryStrings = HttpUtility.ParseQueryString(query[1]); // querystring format fileKey = queryStrings["s"]; if (!string.IsNullOrEmpty(queryStrings["cdv"]) && !Int32.TryParse(queryStrings["cdv"], out version)) { throw new ArgumentException("Could not parse the version in the request"); } try { type = (ClientDependencyType)Enum.Parse(typeof(ClientDependencyType), queryStrings["t"], true); } catch { throw new ArgumentException("Could not parse the type set in the request"); } } else { //get path to parse var path = context.Request.PathInfo.TrimStart('/'); var pathFormat = ClientDependencySettings.Instance.DefaultCompositeFileProcessingProvider.PathBasedUrlFormat; //parse using the parser if (!PathBasedUrlFormatter.Parse(pathFormat, path, out fileKey, out type, out version)) { throw new FormatException("Could not parse the URL path: " + path + " with the format specified: " + pathFormat); } } fileKey = context.Server.UrlDecode(fileKey); if (string.IsNullOrEmpty(fileKey)) { throw new ArgumentException("Must specify a fileset in the request"); } // don't process if the version doesn't match - this would be nice to do but people will get errors if // their html pages are cached and are referencing an old version //if (version != ClientDependencySettings.Instance.Version) // throw new ArgumentException("Configured version does not match request"); byte[] outputBytes = null; //create the webforms page to perform the server side output cache, ensure // the parameters are the same that we are going to use when setting our own custom // caching parameters. Unfortunately server side output cache is tied so directly to // webforms this seems to be the only way to to this. var page = new OutputCachedPage(new OutputCacheParameters { Duration = Convert.ToInt32(TimeSpan.FromDays(10).TotalSeconds), Enabled = true, VaryByParam = "t;s;cdv", VaryByContentEncoding = "gzip;deflate", VaryByHeader = "Accept-Encoding", Location = OutputCacheLocation.Any }); //retry up to 5 times... this is only here due to a bug found in another website that was returning a blank //result. To date, it can't be replicated in VS, but we'll leave it here for error handling support... can't hurt for (int i = 0; i < 5; i++) { outputBytes = ProcessRequestInternal(contextBase, fileKey, type, version, outputBytes, page); if (outputBytes != null && outputBytes.Length > 0) { break; } ClientDependencySettings.Instance.Logger.Error(string.Format("No bytes were returned, this is attempt {0}. Fileset: {1}, Type: {2}, Version: {3}", i, fileKey, type, version), null); } if (outputBytes == null || outputBytes.Length == 0) { ClientDependencySettings.Instance.Logger.Fatal(string.Format("No bytes were returned after 5 attempts. Fileset: {0}, Type: {1}, Version: {2}", fileKey, type, version), null); List <CompositeFileDefinition> fDefs; outputBytes = GetCombinedFiles(contextBase, fileKey, type, out fDefs); } context.Response.ContentType = type == ClientDependencyType.Javascript ? "application/x-javascript" : "text/css"; context.Response.OutputStream.Write(outputBytes, 0, outputBytes.Length); //dispose the webforms page used to do ensure server side output cache page.Dispose(); }
public HttpContextBase GetHttpContext() { var wrapper = new HttpContextWrapper(HttpContext.Current); return(wrapper); }
public OnlineServicesMasterPage() { ContextBase = new HttpContextWrapper(Context); Authorization = new PageAuthorization(); }
void IHttpHandler.ProcessRequest(HttpContext context) { var contextBase = new HttpContextWrapper(context); ClientDependencyType type; string fileKey; int version = 0; if (string.IsNullOrEmpty(context.Request.PathInfo)) { // querystring format fileKey = context.Request["s"]; if (!string.IsNullOrEmpty(context.Request["cdv"]) && !Int32.TryParse(context.Request["cdv"], out version)) { throw new ArgumentException("Could not parse the version in the request"); } try { type = (ClientDependencyType)Enum.Parse(typeof(ClientDependencyType), context.Request["t"], true); } catch { throw new ArgumentException("Could not parse the type set in the request"); } } else { //get path to parse var path = context.Request.PathInfo.TrimStart('/'); var pathFormat = ClientDependencySettings.Instance.DefaultCompositeFileProcessingProvider.PathBasedUrlFormat; //parse using the parser if (!PathBasedUrlFormatter.Parse(pathFormat, path, out fileKey, out type, out version)) { throw new FormatException("Could not parse the URL path: " + path + " with the format specified: " + pathFormat); } } fileKey = context.Server.UrlDecode(fileKey); if (string.IsNullOrEmpty(fileKey)) { throw new ArgumentException("Must specify a fileset in the request"); } byte[] outputBytes = null; //retry up to 5 times... this is only here due to a bug found in another website that was returning a blank //result. To date, it can't be replicated in VS, but we'll leave it here for error handling support... can't hurt for (int i = 0; i < 5; i++) { outputBytes = ProcessRequestInternal(contextBase, fileKey, type, version, outputBytes); if (outputBytes != null && outputBytes.Length > 0) { break; } ClientDependencySettings.Instance.Logger.Error(string.Format("No bytes were returned, this is attempt {0}. Fileset: {1}, Type: {2}, Version: {3}", i, fileKey, type, version), null); } if (outputBytes == null || outputBytes.Length == 0) { ClientDependencySettings.Instance.Logger.Fatal(string.Format("No bytes were returned after 5 attempts. Fileset: {0}, Type: {1}, Version: {2}", fileKey, type, version), null); List <CompositeFileDefinition> fDefs; outputBytes = GetCombinedFiles(contextBase, fileKey, type, out fDefs); } context.Response.ContentType = type == ClientDependencyType.Javascript ? "application/x-javascript" : "text/css"; context.Response.OutputStream.Write(outputBytes, 0, outputBytes.Length); }
private void OnPostMapRequestHandler(object sender, EventArgs e) { HttpContextBase context = new HttpContextWrapper(((HttpApplication)sender).Context); PostMapRequestHandler(context); }
/// <summary> /// Adds server variables for use by the JavaScript. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The event data. /// </param> private void AddServerVariables(object sender, Dictionary<string, object> e) { // Variables. var httpContext = new HttpContextWrapper(HttpContext.Current); var routeData = new RouteData(); var requestContext = new RequestContext(httpContext, routeData); var helper = new UrlHelper(requestContext); var key = MetaConstants.PackageNameCamelCase; // Add server variables. var newEntries = new Dictionary<string, string>() { { "DeleteForm", helper.GetUmbracoApiService<FormsController>(x => x.DeleteForm(null)) }, { "PersistForm", helper.GetUmbracoApiService<FormsController>(x => x.PersistForm(null)) }, { "GetFormInfo", helper.GetUmbracoApiService<FormsController>(x => x.GetFormInfo(null)) }, { "MoveForm", helper.GetUmbracoApiService<FormsController>(x => x.MoveForm(null)) }, { "DeleteConfiguredForm", helper.GetUmbracoApiService<ConfiguredFormsController>(x => x.DeleteConfiguredForm(null)) }, { "PersistConfiguredForm", helper.GetUmbracoApiService<ConfiguredFormsController>(x => x.PersistConfiguredForm(null)) }, { "GetConfiguredFormInfo", helper.GetUmbracoApiService<ConfiguredFormsContentController>(x => x.GetConfiguredFormInfo(null)) }, { "DeleteLayout", helper.GetUmbracoApiService<LayoutsController>(x => x.DeleteLayout(null)) }, { "PersistLayout", helper.GetUmbracoApiService<LayoutsController>(x => x.PersistLayout(null)) }, { "GetLayoutInfo", helper.GetUmbracoApiService<LayoutsController>(x => x.GetLayoutInfo(null)) }, { "GetLayoutKinds", helper.GetUmbracoApiService<LayoutsController>(x => x.GetLayoutKinds()) }, { "MoveLayout", helper.GetUmbracoApiService<LayoutsController>(x => x.MoveLayout(null)) }, { "DeleteValidation", helper.GetUmbracoApiService<ValidationsController>(x => x.DeleteValidation(null)) }, { "PersistValidation", helper.GetUmbracoApiService<ValidationsController>(x => x.PersistValidation(null)) }, { "GetValidationInfo", helper.GetUmbracoApiService<ValidationsController>(x => x.GetValidationInfo(null)) }, { "GetValidationsInfo", helper.GetUmbracoApiService<ValidationsController>(x => x.GetValidationsInfo(null)) }, { "GetValidationKinds", helper.GetUmbracoApiService<ValidationsController>(x => x.GetValidationKinds()) }, { "MoveValidation", helper.GetUmbracoApiService<ValidationsController>(x => x.MoveValidation(null)) }, { "DeleteDataValue", helper.GetUmbracoApiService<DataValuesController>(x => x.DeleteDataValue(null)) }, { "PersistDataValue", helper.GetUmbracoApiService<DataValuesController>(x => x.PersistDataValue(null)) }, { "GetDataValueInfo", helper.GetUmbracoApiService<DataValuesController>(x => x.GetDataValueInfo(null)) }, { "GetDataValuesInfo", helper.GetUmbracoApiService<DataValuesController>(x => x.GetDataValuesInfo(null)) }, { "GetDataValueKinds", helper.GetUmbracoApiService<DataValuesController>(x => x.GetDataValueKinds()) }, { "GetDataValueSuppliers", helper.GetUmbracoApiService<DataValuesController>(x => x.GetDataValueSuppliers()) }, { "MoveDataValue", helper.GetUmbracoApiService<DataValuesController>(x => x.MoveDataValue(null)) }, { "PersistFolder", helper.GetUmbracoApiService<FoldersController>(x => x.PersistFolder(null)) }, { "GetFolderInfo", helper.GetUmbracoApiService<FoldersController>(x => x.GetFolderInfo(null)) }, { "MoveFolder", helper.GetUmbracoApiService<FoldersController>(x => x.MoveFolder(null)) }, { "DeleteFolder", helper.GetUmbracoApiService<FoldersController>(x => x.DeleteFolder(null)) }, { "GetFieldTypes", helper.GetUmbracoApiService<FieldsController>(x => x.GetFieldTypes()) }, { "GetButtonKinds", helper.GetUmbracoApiService<FieldsController>(x => x.GetButtonKinds()) }, { "GetFieldCategories", helper.GetUmbracoApiService<FieldsController>(x => x.GetFieldCategories()) }, { "GetHandlerTypes", helper.GetUmbracoApiService<HandlersController>(x => x.GetHandlerTypes()) }, { "GetResultHandlers", helper.GetUmbracoApiService<HandlersController>(x => x.GetResultHandlers()) }, { "GetTemplates", helper.GetUmbracoApiService<TemplatesController>(x => x.GetTemplates()) }, { "GetEntityChildren", helper.GetUmbracoApiService<EntitiesContentController>(x => x.GetEntityChildren(null)) }, { "GetEntity", helper.GetUmbracoApiService<EntitiesController>(x => x.GetEntity(null)) }, { "GetSubmissions", helper.GetUmbracoApiService<StoredDataController>(x => x.GetSubmissions(null)) }, { "DeleteSubmission", helper.GetUmbracoApiService<StoredDataController>(x => x.DeleteSubmission(null)) }, { "DownloadFile", helper.GetUmbracoApiService<StoredDataDownloadController>(x => x.DownloadFile(null)) }, { "DownloadCsvExport", helper.GetUmbracoApiService<StoredDataDownloadController>(x => x.DownloadCsvExport(null)) }, { "HasConfiguredRecaptcha", helper.GetUmbracoApiService<ServerConfigurationController>(x => x.HasConfiguredRecaptcha()) }, { "EditLayoutBase", "/formulate/formulate/editLayout/" }, { "EditValidationBase", "/formulate/formulate/editValidation/" }, { "EditDataValueBase", "/formulate/formulate/editDataValue/" }, { "Layout.RootId", LayoutConstants.Id }, { "Validation.RootId", ValidationConstants.Id }, { "DataValue.RootId", DataValueConstants.Id }, { "Form.RootId", FormConstants.Id }, { "DuplicateForm", helper.GetUmbracoApiService<FormsController>(x => x.DuplicateForm(null)) }, }; if (e.ContainsKey(key)) { var existing = e[key] as Dictionary<string, string>; foreach (var item in newEntries) { existing[item.Key] = item.Value; } } else { e.Add(key, newEntries); } }
internal void ProcessRequestInternal(HttpContext context) { // enable dynamic validation for this request ValidationUtility.EnableDynamicValidation(context); context.Request.ValidateInput(); try { HttpContextBase contextBase = new HttpContextWrapper(context); //WebSecurity.Context = contextBase; AddVersionHeader(contextBase); WebPageRenderingBase startPage = StartPage.GetStartPage(_webPage, StartPageFileName, WebPageHttpHandler.GetRegisteredExtensions()); // This is also the point where a Plan9 request truly begins execution // We call ExecutePageHierarchy on the requested page, passing in the possible initPage, so that // the requested page can take care of the necessary push/pop context and trigger the call to // the initPage. _webPage.ExecutePageHierarchy(Util.CreatePageContext(context), context.Response.Output, startPage); if (ShouldGenerateSourceHeader(contextBase)) { GenerateSourceFilesHeader(_webPage.PageContext); } } catch (Exception e) { if (!HandleError(e)) { throw; } } }
public void ProcessRequest(HttpContext context) { var contextWrapper = new HttpContextWrapper(context); ProcessInternal(contextWrapper); }
internal static void OnApplicationPostResolveRequestCache(object sender, EventArgs e) { HttpContextBase context = new HttpContextWrapper(((HttpApplication)sender).Context); new WebPageRoute().DoPostResolveRequestCache(context); }
public override async Task <bool> PerformRunAsync(CancellationToken token) { if (_appContext == null) { return(true); // repeat... } if (Suspendable.ScheduledPublishing.CanRun == false) { return(true); // repeat, later } switch (_appContext.GetCurrentServerRole()) { case ServerRole.Slave: Logger.Debug <ScheduledPublishing>("Does not run on slave servers."); return(true); // DO repeat, server role can change case ServerRole.Unknown: Logger.Debug <ScheduledPublishing>("Does not run on servers with unknown role."); return(true); // DO repeat, server role can change } // ensure we do not run if not main domain, but do NOT lock it if (_appContext.MainDom.IsMainDom == false) { LogHelper.Debug <ScheduledPublishing>("Does not run if not MainDom."); return(false); // do NOT repeat, going down } UmbracoContext tempContext = null; try { // DO not run publishing if content is re-loading if (content.Instance.isInitializing == false) { //TODO: We should remove this in v8, this is a backwards compat hack // see notes in CacheRefresherEventHandler // because notifications will not be sent if there is no UmbracoContext // see NotificationServiceExtensions var httpContext = new HttpContextWrapper(new HttpContext(new SimpleWorkerRequest("temp.aspx", "", new StringWriter()))); tempContext = UmbracoContext.EnsureContext( httpContext, _appContext, new WebSecurity(httpContext, _appContext), _settings, UrlProviderResolver.Current.Providers, true); var publisher = new ScheduledPublisher(_appContext.Services.ContentService); var count = publisher.CheckPendingAndProcess(); Logger.Debug <ScheduledPublishing>(() => string.Format("Processed {0} items", count)); } } catch (Exception e) { Logger.Error <ScheduledPublishing>("Failed (see exception).", e); } finally { if (tempContext != null) { tempContext.Dispose(); // nulls the ThreadStatic context } } return(true); // repeat }
public static string GetSiteUrl(this HttpContext context) { HttpContextWrapper wrapper = new HttpContextWrapper(context); return GetSiteUrl(wrapper as HttpContextBase, true); }
private static T GetOwinInjection <T>(IContext context) where T : class { var contextBase = new HttpContextWrapper(HttpContext.Current); return(contextBase.GetOwinContext().Get <T>()); }
protected virtual IAsyncResult BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, object state) { HttpContextBase httpContextBase = new HttpContextWrapper(httpContext); return BeginProcessRequest(httpContextBase, callback, state); }
public override async Task ProcessRequestAsync(HttpContext context) { var contextWrapper = new HttpContextWrapper(context); await ProcessInternal(contextWrapper); }