private static void RenderPartial(string partialName, object model, TextWriter output) { //get a wrapper for the legacy WebForm context var httpCtx = new HttpContextWrapper(HttpContext.Current); //create a mock route that points to the empty controller var rt = new RouteData(); rt.Values.Add("controller", "WebFormController"); //create a controller context for the route and http context var ctx = new ControllerContext( new RequestContext(httpCtx, rt), new WebFormController()); //find the partial view using the view-engine var view = ViewEngines.Engines.FindPartialView(ctx, partialName).View; //create a view context and assign the model var vctx = new ViewContext(ctx, view, new ViewDataDictionary { Model = model }, new TempDataDictionary(), httpCtx.Response.Output); //render the partial view view.Render(vctx, output); }
/// <summary> /// Renders the specified environmental information and appends it to the specified <see cref="T:System.Text.StringBuilder"/>. /// </summary> /// <param name="builder">The <see cref="T:System.Text.StringBuilder"/> to append the rendered data to.</param><param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { try { if (HttpContext.Current == null) return; var context = new HttpContextWrapper(HttpContext.Current); if (context.Request.RequestContext == null) return; var work = context.Request.RequestContext.GetWorkContext(); if (work == null) return; ShellSettings settings; if (!work.TryResolve(out settings)) return; builder.Append("Tenant:"); builder.AppendLine(settings.Name); } catch { } }
public Action<IServiceLocator> Build() { return serviceLocator => serviceLocator .Register(Given<PerRequest>.Then<PerRequest>()) .Register<PerRequest>(Given<ViewDataDictionary>.ConstructWith(x => new ViewDataDictionary())) .Register<PerRequest>(Given<TempDataDictionary>.ConstructWith(x => new TempDataDictionary())) .Register(Given<DummyController>.Then<DummyController>()) .Register<PerRequest>(Given<TempData>.Then<TempData>()) .Register<PerRequest>(Given<ViewModel>.Then<ViewModel>()) .Register(Given<HttpRequestBase>.ConstructWith(x => new HttpRequestWrapper(HttpContext.Current.Request))) .Register(Given<RouteData>.ConstructWith(x => x.GetInstance<RouteCollection>().GetRouteData(x.GetInstance<HttpContextBase>()))) .Register(Given<RequestContext>.Then<RequestContext>()) .Register(Given<RequestContext>.InitializeWith(ctx => { ctx.RouteData.Values["controller"] = ctx.RouteData.GetRequiredString("noun"); ctx.RouteData.Values["action"] = ctx.RouteData.GetRequiredString("verb"); })) .Register(Given<HttpContextBase>.ConstructWith(x => new HttpContextWrapper(HttpContext.Current))) .Register(Given<ControllerContext>.ConstructWith(x => { HttpContextBase context = new HttpContextWrapper(HttpContext.Current); return new ControllerContext(context, x.GetInstance<RequestContext>().RouteData, x.GetInstance<DummyController>()); })) .Register(Given<DummyController>.InitializeWith(controller => { controller.TempData = serviceLocator.GetInstance<TempData>().Data; controller.ViewData = serviceLocator.GetInstance<ViewModel>().ViewData; })); }
public static string RenderSitecorePlaceHolder(string key) { var sublayoutId = GetSublayoutIdFromPlaceHolder(Sitecore.Context.Item[Sitecore.FieldIDs.LayoutField], key); if (!string.IsNullOrEmpty(sublayoutId)) { var layoutItem = Sitecore.Context.Database.GetItem(ID.Parse(sublayoutId)); var controllerName = layoutItem.Fields["Controller"].Value; var actionName = layoutItem.Fields["Action"].Value; HttpContext.Current.RewritePath(string.Concat("/", controllerName, "/", actionName)); RouteData routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current)); if (routeData != null) { var factory = new ControllerFactory(); var httpContextBase = new HttpContextWrapper(HttpContext.Current); var context = new RequestContext(httpContextBase, routeData); Type type = factory.GetController(context, controllerName); if (type != null) { var controller = (Controller)factory.GetController(context, type); var controllerContext = new ControllerContext(httpContextBase, routeData, controller); var viewContext = new ViewContext(controllerContext, new FakeView(), controller.ViewData, controller.TempData, TextWriter.Null); var helper = new HtmlHelper(viewContext, new ViewPage()); return helper.Action(actionName, controllerName).ToHtmlString(); } } HttpContext.Current.RewritePath("default.aspx"); } return ""; }
private void ExecuteErrorPage() { ErrorInfo errorInfo = new ErrorInfo(httpStatusCode, this.exception, HttpContext.Current.Request); RouteData routeData = new RouteData(); routeData.Values.Add("controller", this.config.ErrorControllerName); routeData.Values.Add("action", this.config.ErrorActionName); routeData.Values.Add("errorInfo", errorInfo); HttpContextWrapper httpContextWrapper = new HttpContextWrapper(HttpContext.Current); RequestContext requestContext = new RequestContext(httpContextWrapper, routeData); IControllerFactory controllerFactory = ControllerBuilder.Current.GetControllerFactory(); IController errorController = controllerFactory.CreateController(requestContext, this.config.ErrorControllerName); errorController.Execute(requestContext); if (httpStatusCode > 0) { HttpContext.Current.Response.StatusCode = httpStatusCode; HttpContext.Current.Response.ContentType = "text/html"; } HttpContext.Current.Response.TrySkipIisCustomErrors = true; }
public override ReadOnlyCollection<IAuthorizationPolicy> Authenticate(ReadOnlyCollection<IAuthorizationPolicy> authPolicy, Uri listenUri, ref Message message) { var requestProperties = (HttpRequestMessageProperty)message.Properties[HttpRequestMessageProperty.Name]; var rawAuthHeader = requestProperties.Headers["Authorization"]; AuthenticationHeader authHeader = null; if (AuthenticationHeader.TryDecode(rawAuthHeader, out authHeader)); { var identity = new GenericIdentity(authHeader.Username); var principal = new GenericPrincipal(identity, new string[] { }); var httpContext = new HttpContextWrapper(HttpContext.Current) { User = principal, }; if (httpContext.User != null) return authPolicy; } SendUnauthorizedResponse(); return base.Authenticate(authPolicy, listenUri, ref message); }
void DoPasswordProtect(HttpContextWrapper context) { var request = context.Request; var response = context.Response; //normally this would be some type of abstraction. var username = ConfigurationManager.AppSettings["br-username"]; var password = ConfigurationManager.AppSettings["br-password"]; if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password)) { var data = String.Format("{0}:{1}", username, password); var correctHeader = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(data)); string securityString = request.Headers["Authorization"]; if (securityString == null) goto forceRedirect; if (securityString != correctHeader) goto forceRedirect; goto end; forceRedirect: var host = request.Url.Host.ToLower(); response.AddHeader("WWW-Authenticate", String.Format(@"Basic realm=""{0}""", host)); response.StatusCode = 401; response.End(); end: ; } }
protected void Application_AuthenticateRequest(object sender, EventArgs e) { var context = new HttpContextWrapper(HttpContext.Current); if (!SecurityManager.TryAuthenticateRequest(context)) { var route = RouteTable.Routes.GetRouteData(context); // If the route is not registerd in the WebAPI RouteTable // then it's not an API route, which means it's a resource (*.js, *.css, *.cshtml), not authenticated. // If the route doesn't have authenticated value assume true var isAuthenticated = route != null && (route.Values["authenticated"] == null || (bool)route.Values["authenticated"]); var isFile = FileSystemHelpers.FileExists(HostingEnvironment.MapPath($"~{context.Request.Url.AbsolutePath.Replace('/', '\\')}")); if (isAuthenticated) { context.Response.Headers["LoginUrl"] = SecurityManager.GetLoginUrl(context); context.Response.StatusCode = 403; // Forbidden } else if (context.Request.Url.AbsolutePath.Equals("/api/health", StringComparison.OrdinalIgnoreCase)) { context.Response.WriteFile(HostingEnvironment.MapPath("~/health.html")); context.Response.Flush(); context.Response.End(); } else if (!isFile) { context.Response.RedirectLocation = Environment.GetEnvironmentVariable("ACOM_MARKETING_PAGE") ?? $"{context.Request.Url.GetLeftPart(UriPartial.Authority)}/signin"; context.Response.StatusCode = 302; context.Response.End(); } } }
/// <summary> /// The process user authorization. /// </summary> /// <param name="context">The HTTP context.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The response message. /// </returns> public Task<AccessTokenResponse> ProcessUserAuthorizationAsync(HttpContextBase context = null, CancellationToken cancellationToken = default(CancellationToken)) { if (context == null) { context = new HttpContextWrapper(HttpContext.Current); } return this.webConsumer.ProcessUserAuthorizationAsync(context.Request.Url, cancellationToken: cancellationToken); }
public AspNetWebApplicationUrl() { if(HttpContext.Current != null) { Context = new HttpContextWrapper(HttpContext.Current); } }
// GET: api/InvestorPerson/5 //[ResponseType(typeof(z_Person))] public async Task <JsonResult <z_Person> > GetPerson(int id) { IUser currentUser = null; var userTicket = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current).GetUmbracoAuthTicket(); if (userTicket != null) { currentUser = ApplicationContext.Services.UserService.GetByUsername(userTicket.Name); } if (currentUser == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } z_Person person = await db.z_Person.FindAsync(id); if (person == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return(Json(person)); }
public void Init(HttpApplication app) { app.BeginRequest += (sender, args) => { var context = new HttpContextWrapper(((HttpApplication)sender).Context); // ReSharper disable PossibleNullReferenceException var decodedPath = context.Server.UrlDecode(context.Request.Url.AbsolutePath); // ReSharper restore PossibleNullReferenceException if (decodedPath == null) { throw new HttpException((int)HttpStatusCode.BadRequest, "Bad request"); } var path = decodedPath.ToLowerInvariant(); foreach (var action in _actions.Where(action => action.CanHandle(path))) { action.DoExecute(context, path); context.ApplicationInstance.CompleteRequest(); break; } }; }
public void CreateController_WithRouteData_CreatesControllerInstance() { var context = new HttpContextWrapper(new HttpContext( new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null))); context.Items["CurrentResourcePackage"] = "test"; var layoutTemplateBuilder = new LayoutRenderer(); Controller dummyController = null; SystemManager.RunWithHttpContext(context, () => { var routeData = new RouteData(); routeData.Values.Add("controller", "dummy"); dummyController = layoutTemplateBuilder.CreateController(routeData); }); Assert.IsNotNull(dummyController); Assert.IsTrue(dummyController != null); Assert.IsTrue(dummyController.ControllerContext != null); Assert.IsTrue(dummyController.ControllerContext.RouteData != null); Assert.IsTrue(dummyController.ControllerContext.RouteData.Values != null); Assert.IsTrue(dummyController.ControllerContext.RouteData.Values.ContainsKey("controller")); Assert.IsTrue(dummyController.ControllerContext.RouteData.Values["controller"] != null); Assert.AreEqual<string>(dummyController.ControllerContext.RouteData.Values["controller"].ToString(), "dummy"); }
public static string ParseRazor(string virtualPath, object model) { string pageVPath = virtualPath; try { Type t = BuildManager.GetCompiledType(pageVPath); if (t != null) { HttpContextWrapper wrapper = new HttpContextWrapper(HttpContext.Current); object inst = Activator.CreateInstance(t); System.Web.WebPages.WebPage webpage = inst as System.Web.WebPages.WebPage; webpage.VirtualPath = pageVPath; StringWriter writer = new StringWriter(); webpage.ExecutePageHierarchy(new System.Web.WebPages.WebPageContext(wrapper, webpage, model), writer, webpage); string content = writer.ToString(); return content; } } catch (Exception ex) { Utils.Log(string.Format("RazorHelper, ParseRazor, VirtualPath: {0}", virtualPath), ex); // return the error message since it will usually contain parsing // details when the Razor markup/syntax is invalid. this will help // when debugging, so the error log does not need to be checked. return ex.Message; } return null; }
public void InitHelpers() { var httpContext = new HttpContextWrapper(HttpContext.Current); var handler = httpContext.CurrentHandler as MvcHandler; if (handler == null) throw new InvalidOperationException("Unable to run template outside of ASP.NET MVC"); }
private void OnBeginRequest(Object sender, EventArgs args) { HttpApplication application = (HttpApplication)sender; HttpContextBase currentContext = new HttpContextWrapper(HttpContext.Current); var userCulture = CEngine.Instance.GetCultureByUserLanguages(application.Request.UserLanguages); if (currentContext.Request.Url.AbsolutePath.Equals("") || currentContext.Request.Url.AbsolutePath.Equals("/")) { currentContext.Response.RedirectToRoute("Default", new { locale = userCulture }); return; } RouteData routeData = RouteTable.Routes.GetRouteData(currentContext); var cultureName = routeData.Values[CEngine.Instance.CultureKey]; if (cultureName != null) { if (CEngine.Instance.IsSupported(cultureName.ToString())) { CEngine.Instance.SetCultureForThread(cultureName.ToString()); } else { currentContext.Response.RedirectToRoute("Default", new { locale = userCulture }); } } else { CEngine.Instance.SetCultureForThread(userCulture); } }
public static string RenderViewToString(string controllerName, string viewName, object viewData, List<KeyValuePair<string, object>> additionalData) { var context = HttpContext.Current; var contextBase = new HttpContextWrapper(context); var routeData = new RouteData(); routeData.Values.Add("controller", controllerName); var controllerContext = new ControllerContext(contextBase, routeData, new EmptyController()); var razorViewEngine = new RazorViewEngine(); var razorViewResult = razorViewEngine.FindView(controllerContext, viewName, "", false); ViewDataDictionary vdd = new ViewDataDictionary(viewData); if (additionalData != null && additionalData.Any()) additionalData.ForEach(vdd.Add); var writer = new StringWriter(); var viewContext = new ViewContext(controllerContext, razorViewResult.View, vdd, new TempDataDictionary(), writer); razorViewResult.View.Render(viewContext, writer); return writer.ToString(); }
public IList<RouteData> GetMatches(string virtualPath) { HttpContextBase context = new HttpContextWrapper(HttpContext.Current); return GetMatches(virtualPath, "GET", context); }
public CommonController() { //HttpContextBase httpContext, HttpContextBase abstractContext = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current); this._httpContext = abstractContext; }
void context_BeginRequest(object sender, EventArgs e) { var application = (HttpApplication)sender; var context = new HttpContextWrapper(application.Context); DoPasswordProtect(context); }
protected void Application_Error() { var exception = Server.GetLastError(); var httpException = exception as HttpException; Response.Clear(); Server.ClearError(); var routeData = new RouteData(); routeData.Values["controller"] = "Errors"; routeData.Values["action"] = "General"; routeData.Values["exception"] = exception; Response.StatusCode = 500; if (httpException != null) { Response.StatusCode = httpException.GetHttpCode(); switch (Response.StatusCode) { //case 403: // routeData.Values["action"] = "Http403"; // break; case 404: routeData.Values["action"] = "Http404"; break; } } // Avoid IIS7 getting in the middle Response.TrySkipIisCustomErrors = true; IController errorsController = new ErrorsController(); HttpContextWrapper wrapper = new HttpContextWrapper(Context); var rc = new RequestContext(wrapper, routeData); errorsController.Execute(rc); }
public string For(string controller, string action, IDictionary<string, object> values) { var httpContextWrapper = new HttpContextWrapper(HttpContext.Current); var urlHelper = new UrlHelper(new RequestContext(httpContextWrapper, RouteTable.Routes.GetRouteData(httpContextWrapper))); return FullApplicationPath(httpContextWrapper.Request) + urlHelper.Action(action, controller, new RouteValueDictionary(values)); }
/// <summary> /// Enrich the log event with the current ASP.NET user name, if User.Identity.IsAuthenticated is true.</summary> /// <param name="logEvent">The log event to enrich.</param> /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param> public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) { if (logEvent == null) throw new ArgumentNullException("logEvent"); var userName = _noneUsername; if (HttpContext.Current != null) { var context = new HttpContextWrapper(HttpContext.Current); if (context.User != null) { if (context.User.Identity == null || context.User.Identity.IsAuthenticated == false) { if (_anonymousUsername != null) userName = _anonymousUsername; } else { userName = context.User.Identity.Name; } } } if (userName == null) return; var userNameProperty = new LogEventProperty(UserNamePropertyName, new ScalarValue(userName)); logEvent.AddPropertyIfAbsent(userNameProperty); }
protected void Application_Error(object sender, EventArgs e) { Exception lastError = Server.GetLastError(); Server.ClearError(); int statusCode = 0; if (lastError.GetType() == typeof(HttpException)) { statusCode = ((HttpException) lastError).GetHttpCode(); } else { // Not an HTTP related error so this is a problem in our code, set status to // 500 (internal server error) statusCode = 500; } HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context); RouteData routeData = new RouteData(); routeData.Values.Add("controller", "Error"); routeData.Values.Add("action", "Index"); routeData.Values.Add("statusCode", statusCode); routeData.Values.Add("exception", lastError); routeData.Values.Add("isAjaxRequet", contextWrapper.Request.IsAjaxRequest()); IController controller = new ErrorController(); RequestContext requestContext = new RequestContext(contextWrapper, routeData); controller.Execute(requestContext); Response.End(); }
/// <summary> /// Creates the proper CSS link reference within the target CSHTML page's head section /// </summary> /// <param name="virtualPath">The relative path of the image to be displayed, or its directory</param> /// <returns>Link tag if the file is found.</returns> public static ViewEngines.Razor.IHtmlString ImportStylesheet(string virtualPath) { ImageOptimizations.EnsureInitialized(); if (Path.HasExtension(virtualPath)) virtualPath = Path.GetDirectoryName(virtualPath); var httpContext = new HttpContextWrapper(HttpContext.Current); var cssFileName = ImageOptimizations.LinkCompatibleCssFile(httpContext.Request.Browser) ?? ImageOptimizations.LowCompatibilityCssFileName; virtualPath = Path.Combine(virtualPath, cssFileName); var physicalPath = HttpContext.Current.Server.MapPath(virtualPath); if (File.Exists(physicalPath)) { var htmlTag = new TagBuilder("link"); htmlTag.MergeAttribute("href", ResolveUrl(virtualPath)); htmlTag.MergeAttribute("rel", "stylesheet"); htmlTag.MergeAttribute("type", "text/css"); htmlTag.MergeAttribute("media", "all"); return new NonEncodedHtmlString(htmlTag.ToString(TagRenderMode.SelfClosing)); } return null; }
/// <summary> /// Checks if any assigned filters validate the current handler, if so then assigns any filter /// that CanExecute to the response filter chain. /// /// Checks if the request MIME type matches the list of mime types specified in the config, /// if it does, then it compresses it. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void HandleRequest(object sender, EventArgs e) { var app = (HttpApplication)sender; var http = new HttpContextWrapper(app.Context); //if debug is on, then don't compress if (!http.IsDebuggingEnabled) { //IMPORTANT: Compression must be assigned before any other filters are executed! // if compression is applied after the response has been modified then we will end // up getting encoding errors. // The compressor will not attempt to compress if the current filter is not ASP.Net's // original filter. The filter could be changed by developers or perhaps even hosting // providers (based on their machine.config with their own modules. var c = new MimeTypeCompressor(new HttpContextWrapper(app.Context)); c.AddCompression(); } var filters = LoadFilters(http); if (ValidateCurrentHandler(filters)) { ExecuteFilter(http, filters); } }
protected void Application_AuthenticateRequest(Object sender, EventArgs e) { var context = new HttpContextWrapper(HttpContext.Current); if (!string.IsNullOrEmpty(AuthSettings.EnableAuth) && AuthSettings.EnableAuth.Equals(false.ToString(), StringComparison.OrdinalIgnoreCase)) { context.User = new TryWebsitesPrincipal(new TryWebsitesIdentity("*****@*****.**", null, "Local")); return; } if (!SecurityManager.TryAuthenticateSessionCookie(context)) { if (SecurityManager.HasToken(context)) { // This is a login redirect SecurityManager.AuthenticateRequest(context); return; } var route = RouteTable.Routes.GetRouteData(context); // If the route is not registerd in the WebAPI RouteTable // then it's not an API route, which means it's a resource (*.js, *.css, *.cshtml), not authenticated. // If the route doesn't have authenticated value assume true var isAuthenticated = route != null && (route.Values["authenticated"] == null || (bool)route.Values["authenticated"]); if (isAuthenticated) { SecurityManager.AuthenticateRequest(context); } else if (context.IsBrowserRequest()) { SecurityManager.HandleAnonymousUser(context); } } }
public static IResolverScope GetRequestScope(this IResolver resolver, HttpContextBase context = null) { if (resolver == null) throw new ArgumentNullException("resolver"); if (context == null) context = new HttpContextWrapper(HttpContext.Current); var item = context.Items[_requestKey]; if (item == null) { lock (context.Items.SyncRoot) // Lock on different object only being used to get the Scope to minimize locking? { item = context.Items[_requestKey]; if (item == null) { var scope = resolver.GetScope(); context.Items[_requestKey] = scope; // Register for automatica disposal at end of request context.RegisterForDispose(scope); return scope; } } } return (IResolverScope)item; }
protected void Application_Error(object sender, EventArgs e) { Exception lastError = Server.GetLastError(); Server.ClearError(); int statusCode = 0; if (lastError.GetType() == typeof(HttpException)) { statusCode = ((HttpException)lastError).GetHttpCode(); } else { statusCode = 500; } HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context); RouteData routeData = new RouteData(); routeData.Values.Add("controller", "Error"); routeData.Values.Add("action", "Index"); routeData.Values.Add("statusCode", statusCode); routeData.Values.Add("exception", lastError); IController controller = new ErrorController(); RequestContext requestContext = new RequestContext(contextWrapper, routeData); controller.Execute(requestContext); Response.End(); }
protected void Application_Error() { var httpContext = HttpContext.Current; if (httpContext == null) return; var context = new HttpContextWrapper(System.Web.HttpContext.Current); var routeData = RouteTable.Routes.GetRouteData(context); var requestContext = new RequestContext(context, routeData); /* when the request is ajax the system can automatically handle a mistake with a JSON response. then overwrites the default response */ if (requestContext.HttpContext.Request.IsAjaxRequest()) { httpContext.Response.Clear(); var controllerName = requestContext.RouteData.GetRequiredString("controller"); var factory = ControllerBuilder.Current.GetControllerFactory(); var controller = factory.CreateController(requestContext, controllerName); var controllerContext = new ControllerContext(requestContext, (ControllerBase)controller); var jsonResult = new JsonResult { Data = new {success = false, serverError = "500"}, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; jsonResult.ExecuteResult(controllerContext); httpContext.Response.End(); } else { httpContext.Response.Redirect("~/Error"); } }
protected void Application_Error(object sender, EventArgs e) { var ex = Server.GetLastError(); if (ex != null) { var bhEx = ex as FlhException; var context = new HttpContextWrapper(Context); var errorCode = bhEx == null ? ErrorCode.ServerError : bhEx.ErrorCode; var errorMsg = bhEx == null ? ex.ToString() : bhEx.Message; if (context.Request.IsAjaxRequest()) { Context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new Web.JsonResultEntry { Code = errorCode, Message = errorMsg })); } else { IController ec = new Controllers.ErrorController(); var routeData = new RouteData(); routeData.Values["action"] = "index"; routeData.Values["controller"] = "error"; routeData.DataTokens["code"] = errorCode; routeData.DataTokens["msg"] = errorMsg; ec.Execute(new RequestContext(context, routeData)); } Server.ClearError(); } }
protected void AddBreadcrumb(string title, string targetAction, string targetController, RouteValueDictionary routeValues, int? index = null) { HttpContextWrapper httpContextWrapper = new HttpContextWrapper(System.Web.HttpContext.Current); UrlHelper urlHelper = new UrlHelper(new RequestContext(httpContextWrapper, new RouteData())); AddBreadcrumb(title, urlHelper.Action(targetAction, targetController, routeValues), index); }
private PageContext CreatePageContext(System.Web.HttpContextWrapper context) { PageContext pageContext = new PageContext(); RouteData routeData = CreateRouteData(); pageContext.RequestContext = this.CreateRequestContext(context, routeData); return(pageContext); }
private RequestContext CreateRequestContext(System.Web.HttpContextWrapper httpContextWrapper, RouteData routeData) { return(new RequestContext { HttpContext = httpContextWrapper, RouteData = routeData }); }
public void Import() { string userName = string.Empty; bool isLoggedInUser = false; IUser currentUser = null; var userTicket = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current).GetUmbracoAuthTicket(); if (userTicket != null) { isLoggedInUser = true; currentUser = ApplicationContext.Services.UserService.GetByUsername(userTicket.Name); } if (isLoggedInUser) { userName = currentUser.Name; if (currentUser.IsAdmin()) { } else { //currentUser.UserState. FormsAuthentication.SignOut(); //return RedirectToCurrentUmbracoPage(); } } else { userName = ""; } //var startPage = Umbraco.TypedContentAtRoot().First(); //var settingsPage = startPage?.Descendants("settingsPage").FirstOrDefault(); ////this gets the parent node. under that page it will our import controller generate the new pages. //var pageId = settingsPage?.GetPropertyValue<int>("PressReleaserNode"); ////Releases listofReleases = PressReleasesService.GetTtData(); //Releases listofReleases = MyCoolTaskClass.GetTtData(); //List<PressRelease> releasesList = new List<PressRelease>(); //foreach (PressRelease pressRelease in listofReleases.releases) //{ // releasesList.Add(pressRelease); //} //if (pageId != null) //{ // CreatingContent((int)pageId, releasesList); //} }
///// <summary> ///// Get Header. ///// </summary> ///// <param name="request">Request message.</param> ///// <param name="key">Key to find.</param> ///// <returns>Return header value.</returns> //public static string GetHeader(HttpRequestMessage request, string key) //{ // IEnumerable<string> keys = null; // if (!request.Headers.TryGetValues(key, out keys)) // { // return null; // } // else // { // string[] values = new List<string>(keys).ToArray(); // return values[0]; // } //} /// <summary> /// Get User IP. /// </summary> /// <param name="request">Request message.</param> /// <param name="key">Key to find.</param> /// <returns>Return header value.</returns> public static string GetUserIP(System.Web.HttpContextWrapper httpContextWrapper) { var request = httpContextWrapper.Request; var userIPGroup = request.ServerVariables["HTTP_X_FORWARDED_FOR"]; string userIP = string.Empty; if (!string.IsNullOrEmpty(userIPGroup)) { string[] rangeIP = userIPGroup.Split(','); int le = rangeIP.Length - 1; userIP = rangeIP[le]; } else { userIP = request.ServerVariables["REMOTE_ADDR"]; } return(userIP); }
private void context_EndRequest(object sender, EventArgs e) { var app = (HttpApplication)sender; var pageExtension = System.IO.Path.GetExtension(app.Context.Request.Path); if (GlobalConfiguration.Configuration.BanishedExtensions.Contains(pageExtension)) { return; } var ctxbase = new System.Web.HttpContextWrapper(app.Context); var builder = new PageTrack(ctxbase); Task.Run(async() => { await builder.SendAsync(); } ); }
/// <summary> /// API全局异常处理 /// </summary> /// <param name="filterContext"></param> public override void OnException(HttpActionExecutedContext filterContext) { //写日志 string controllerName = filterContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName; string actionName = filterContext.ActionContext.ActionDescriptor.ActionName; string httpMethod = filterContext.Request.Method.ToString(); string Msg = filterContext.Exception.Message; string Data = ""; System.Web.HttpContextWrapper context = ((System.Web.HttpContextWrapper)filterContext.Request.Properties["MS_HttpContext"]); using (StreamReader sr = new StreamReader(context.Request.InputStream)) { Data = sr.ReadToEnd(); } BLL.ErrLogBLL.AddLog(controllerName, actionName, Msg, Data); //返回错误信息 Exception e = filterContext.Exception; filterContext.Response = CommonHelper.ResultHelper.Failed(Msg); base.OnException(filterContext); }
// // GET: /HelloWorld/Index public string Index() { //string domainAndName = Page.User.Identity.Name; //string[] infoes = domainAndName.Split(new char[1] { '\\' }, StringSplitOptions.RemoveEmptyEntries); //string userDomainName = ""; //string userName = ""; //if (infoes.Length > 1) //{ // userDomainName = infoes[0]; // userName = infoes[1]; //} // 判断域用户是否登录 var context = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current); if (context.User.Identity.IsAuthenticated) { return("用戶已经登录!"); } UserInfo userInfo = UserHelper.GetCurrentUserInfo(System.Web.HttpContext.Current); return("This is my <b>Default</b> action method..." + GetUserLoginName(System.Web.HttpContext.Current)); }
/// <summary> /// 执行结束 /// </summary> /// <param name="filterContext"></param> public override void OnActionExecuted(HttpActionExecutedContext filterContext) { if (filterContext.Request.Properties.ContainsKey(Key)) { var stopWatch = filterContext.Request.Properties[Key] as Stopwatch; if (stopWatch != null) { stopWatch.Stop(); System.Web.HttpContextWrapper context = ((System.Web.HttpContextWrapper)filterContext.Request.Properties["MS_HttpContext"]); string controllerName = filterContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = filterContext.ActionContext.ActionDescriptor.ActionName; string httpMethod = filterContext.Request.Method.ToString(); double rt = stopWatch.Elapsed.TotalSeconds; if (rt > 2) { BLL.ErrLogBLL.AddLog(controllerName, actionName, "Api执行时间", rt); } } } //base.OnActionExecuted(filterContext); }
public void Configuration(IAppBuilder app) { try { #region "SSL settings" // Remove insecure protocols (SSL3, TLS 1.0, TLS 1.1) ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3; ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Tls; ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Tls11; // Add TLS 1.2 ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; #endregion Auth0ConfigBase config = Auth0ConfigBase.GetConfig(Constants.PROVIDER_NAME, Helpers.FirstPortalID); System.Web.Helpers.AntiForgeryConfig.UniqueClaimTypeIdentifier = System.Security.Claims.ClaimTypes.NameIdentifier; // Configure Auth0 parameters string auth0Domain = config.Domain; string auth0ClientId = config.ClientID; // Enable the Cookie saver middleware to work around a bug in the OWIN implementation app.UseKentorOwinCookieSaver(); // Set Cookies as default authentication type app.SetDefaultSignInAsAuthenticationType(Constants.AUTH_TYPE); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = Constants.AUTH_TYPE, CookieName = Constants.AUTH_COOKIE_NAME, }); // Configure Auth0 authentication app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { AuthenticationType = Constants.AUTH_TYPE, Authority = $"https://{auth0Domain}", ClientId = auth0ClientId, Scope = "openid profile email", ResponseType = OpenIdConnectResponseType.CodeIdToken, TokenValidationParameters = new TokenValidationParameters { NameClaimType = System.Security.Claims.ClaimTypes.NameIdentifier }, Notifications = new OpenIdConnectAuthenticationNotifications { RedirectToIdentityProvider = notification => { DotNetNuke.Entities.Portals.PortalSettings _portalSettings = null; #region "Get settings from current DNN portal" if (notification.OwinContext.Environment["System.Web.HttpContextBase"] != null && notification.OwinContext.Environment["System.Web.HttpContextBase"] is System.Web.HttpContextWrapper) { System.Web.HttpContextWrapper context = notification.OwinContext.Environment["System.Web.HttpContextBase"] as System.Web.HttpContextWrapper; if (context.Items["PortalSettings"] != null && context.Items["PortalSettings"] is DotNetNuke.Entities.Portals.PortalSettings) { _portalSettings = context.Items["PortalSettings"] as DotNetNuke.Entities.Portals.PortalSettings; } } #endregion #region "Get provider settings" Auth0ConfigBase _providerConfig = null; if (_portalSettings != null) { _providerConfig = Auth0ConfigBase.GetConfig(Constants.PROVIDER_NAME, _portalSettings.PortalId); } else { logger.Debug("Can't obtain DNN settings, login process terminated!!"); } #endregion #region "Set Auth0 coordinates according to the current DNN portal" if (_portalSettings != null && notification.ProtocolMessage.RequestType != OpenIdConnectRequestType.Logout) { notification.Options.Authority = $"https://{_providerConfig.Domain}"; notification.Options.ClientId = _providerConfig.ClientID; notification.Options.ClientSecret = _providerConfig.ClientSecret; notification.Options.RedirectUri = _providerConfig.RedirectUri; notification.Options.CallbackPath = Microsoft.Owin.PathString.FromUriComponent("/Default.aspx"); notification.ProtocolMessage.ClientId = _providerConfig.ClientID; notification.ProtocolMessage.ClientSecret = _providerConfig.ClientSecret; notification.ProtocolMessage.RedirectUri = _providerConfig.RedirectUri; } #endregion #region "Log-off code snippet" else if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout) { var logoutUri = $"https://{_providerConfig.Domain}/v2/logout?client_id={_providerConfig.ClientID}"; var postLogoutUri = _providerConfig.PostLogoutRedirectUri; if (!string.IsNullOrEmpty(postLogoutUri)) { if (postLogoutUri.StartsWith("/")) { // transform to absolute var request = notification.Request; postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri; } logoutUri += $"&returnTo={ Uri.EscapeDataString(postLogoutUri)}"; } notification.Response.Redirect(logoutUri); notification.HandleResponse(); } #endregion #region "Output some diagnistic info" if (_providerConfig != null && _providerConfig.IsDiagnosticModeEnabled) { logger.Debug(string.Format("Redirecting to '{0}' using following coordinates:", notification.Options.Authority)); logger.Debug("Client id: " + notification.Options.ClientId); logger.Debug("Redirect uri: " + notification.Options.RedirectUri); logger.Debug("Callback path: " + notification.Options.CallbackPath); } #endregion return(Task.FromResult(0)); }, AuthorizationCodeReceived = async context => { DotNetNuke.Entities.Portals.PortalSettings _portalSettings = null; #region "Get settings from current DNN portal" if (context.OwinContext.Environment["System.Web.HttpContextBase"] != null && context.OwinContext.Environment["System.Web.HttpContextBase"] is System.Web.HttpContextWrapper) { System.Web.HttpContextWrapper _context = context.OwinContext.Environment["System.Web.HttpContextBase"] as System.Web.HttpContextWrapper; if (_context.Items["PortalSettings"] != null && _context.Items["PortalSettings"] is DotNetNuke.Entities.Portals.PortalSettings) { _portalSettings = _context.Items["PortalSettings"] as DotNetNuke.Entities.Portals.PortalSettings; } } #endregion #region "Get provider settings" Auth0ConfigBase _providerConfig = null; if (_portalSettings != null) { _providerConfig = Auth0ConfigBase.GetConfig(Constants.PROVIDER_NAME, _portalSettings.PortalId); } else { throw new ArgumentNullException("Can't obtain DNN settings, login process terminated!!"); } #endregion GS.Auth0.Components.UserController userController = new GS.Auth0.Components.UserController(); //get or create DNN user DotNetNuke.Entities.Users.UserInfo _userInfo = userController.User_Create(context.AuthenticationTicket.Identity.Name, _portalSettings, _providerConfig.IsDiagnosticModeEnabled); if (_userInfo != null) { //update DNN user profile userController.User_Update( _userInfo, context.AuthenticationTicket.Identity?.FindFirst(c => c.Type == "nickname")?.Value, context.AuthenticationTicket.Identity?.FindFirst(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value, _portalSettings.PortalId, _providerConfig.IsDiagnosticModeEnabled); DotNetNuke.Security.Membership.UserLoginStatus loginStatus = DotNetNuke.Security.Membership.UserLoginStatus.LOGIN_FAILURE; UserInfo objUserInfo = DotNetNuke.Entities.Users.UserController.ValidateUser(_portalSettings.PortalId, context.AuthenticationTicket.Identity.Name, "", Constants.PROVIDER_NAME, "", _portalSettings.PortalName, "", ref loginStatus); //set type of current authentication provider DotNetNuke.Services.Authentication.AuthenticationController.SetAuthenticationType(Constants.AUTH_TYPE); DotNetNuke.Entities.Users.UserController.UserLogin(_portalSettings.PortalId, _userInfo, _portalSettings.PortalName, context.OwinContext.Request.RemoteIpAddress, false); } else { throw new ArgumentNullException(string.Format("Can't create or get user '{0}' from DNN.", context.AuthenticationTicket.Identity.Name)); } await Task.FromResult(0); }, AuthenticationFailed = (context) => { //get the error message and send it to the DNN login page DotNetNuke.Entities.Portals.PortalSettings _portalSettings = null; #region "Get settings from current DNN portal" if (context.OwinContext.Environment["System.Web.HttpContextBase"] != null && context.OwinContext.Environment["System.Web.HttpContextBase"] is System.Web.HttpContextWrapper) { System.Web.HttpContextWrapper _context = context.OwinContext.Environment["System.Web.HttpContextBase"] as System.Web.HttpContextWrapper; if (_context.Items["PortalSettings"] != null && _context.Items["PortalSettings"] is DotNetNuke.Entities.Portals.PortalSettings) { _portalSettings = _context.Items["PortalSettings"] as DotNetNuke.Entities.Portals.PortalSettings; } } #endregion #region "Get provider settings" Auth0ConfigBase _providerConfig = null; if (_portalSettings != null) { _providerConfig = Auth0ConfigBase.GetConfig(Constants.PROVIDER_NAME, _portalSettings.PortalId); } else { logger.Error("Can't obtain DNN settings from 'AuthenticationFailed' event, login process terminated!!"); } #endregion if (_providerConfig.IsDiagnosticModeEnabled) { logger.Error(string.Format("OIDC authentication failed, details: {0}", context.Exception)); } string redirectUrl = DotNetNuke.Common.Globals.NavigateURL(_portalSettings.LoginTabId, "Login", new string[] { Constants.ALERT_QUERY_STRING + "=" + context.Exception.Message }); context.Response.Redirect(redirectUrl); context.HandleResponse(); return(Task.FromResult(0)); }, #region "Rest of 'Notification' methods, not in use for now." //SecurityTokenValidated = notification => //{ // return Task.FromResult(0); //}, //MessageReceived = (context) => //{ // return Task.FromResult(0); //}, #endregion }, }); } catch (Exception ex) { logger.Error(ex); } }
public void ProcessRequest(HttpContext context) { try { HttpContextBase abstractContext = new System.Web.HttpContextWrapper(context); var urlRewriteProcessor = new InboundRewriteProcessor(); HttpRequestArgs requestArgs = new HttpRequestArgs(abstractContext, HttpRequestType.Begin); var requestUri = context.Request.Url; var siteContext = SiteContextFactory.GetSiteContext(requestUri.Host, requestUri.AbsolutePath, requestUri.Port); if (siteContext != null) { using (new SiteContextSwitcher(siteContext)) { urlRewriteProcessor.Process(requestArgs); } } } catch (ThreadAbortException) { // swallow this exception because we may have called Response.End } catch (HttpException) { // we want to throw http exceptions, but we don't care about logging them in Sitecore throw; } catch (Exception ex) { if (ex is HttpException || ex is ThreadAbortException) { return; } // log it in sitecore Log.Error(this, ex, "Error in UrlRewriteHandler."); // throw; // don't re-throw the error, but instead let it fall through } // if we have come this far, the url rewrite processor didn't match on anything so the request is passed to the static request handler // Serve static content: IHttpHandler staticFileHanlder = null; try { var systemWebAssemblyName = GetType() .Assembly.GetReferencedAssemblies() .First(assembly => assembly.FullName.StartsWith("System.Web, ")); var systemWeb = AppDomain.CurrentDomain.Load(systemWebAssemblyName); var staticFileHandlerType = systemWeb.GetType("System.Web.StaticFileHandler", true); staticFileHanlder = Activator.CreateInstance(staticFileHandlerType, true) as IHttpHandler; } catch (Exception) { } if (staticFileHanlder != null) { try { staticFileHanlder.ProcessRequest(context); } catch (HttpException httpException) { if (httpException.GetHttpCode() == 404) { HandleNotFound(context); } else { throw; } } } }
internal static string GetOrSetClientId(this HttpContext ctx, string cookieName, out bool isNewSession) { var ctxbase = new System.Web.HttpContextWrapper(ctx); return(GetOrSetClientId(ctxbase, cookieName, out isNewSession)); }
// GET: api/InvestorPerson public JsonResult <List <GetNbrOfQVM> > GetPersons() // JsonResult<DbSet<z_Person>> { IUser currentUser = null; var userTicket = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current).GetUmbracoAuthTicket(); if (userTicket != null) { currentUser = ApplicationContext.Services.UserService.GetByUsername(userTicket.Name); var j = Request.RequestUri; var k = System.Web.HttpContext.Current.Request.UrlReferrer; if (currentUser == null || !InvestorDashboardPermission(currentUser.Id)) { var j1 = Request.RequestUri; var k1 = System.Web.HttpContext.Current.Request.UrlReferrer; if (k1 == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } else { return(null); } } else { // var j = Request.RequestUri; //var k = System.Web.HttpContext.Current.Request.UrlReferrer; //var h = new JsonSerializerSettings(); // HttpContext.Current.Response.ContentType = "application/json"; var k1 = System.Web.HttpContext.Current.Request.UrlReferrer; if (k1 == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } var res = new List <GetNbrOfQVM>(); foreach (var p in db.z_Person) { GetNbrOfQVM gbnr = new GetNbrOfQVM(); gbnr.Id = p.PersonID; gbnr.FirstName = p.FirstName; gbnr.LastName = p.LastName; gbnr.Email = p.Email; gbnr.NbrOf = GetNbrOfInvest(gbnr.Id); res.Add(gbnr); } return(Json(res)); //Json(db.z_Person); } } else { throw new HttpResponseException(HttpStatusCode.NotFound); } }
private void InitializeContext(System.Web.HttpContextWrapper httpContextWrapper) { SetNativeContext(httpContextWrapper); }
public async Task <HttpResponseMessage> UploadFileToServer() { var US = ApplicationContext.Current.Services.UserService; HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest); // get the user id int userId = 0; try { var userTicket = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current).GetUmbracoAuthTicket(); if (userTicket != null) { var currentUser = US.GetByUsername(userTicket.Name); userId = US.GetByUsername(currentUser.Username).Id; } } catch (Exception err) { LogHelper.Error(typeof(uSCORMController), "Failed to retrieve user identifier. " + err.Message, err); throw (err); } if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string userUploadFolder = HttpContext.Current.Server.MapPath(baseUploadFolder + "user-" + userId); if (!Directory.Exists(userUploadFolder)) { Directory.CreateDirectory(userUploadFolder); } // save uploaded file to user folder var provider = new CustomMultipartFormDataStreamProvider(userUploadFolder); var result = await Request.Content.ReadAsMultipartAsync(provider); var fileName = Path.GetFileName(result.FileData.First().LocalFileName); var nodeId = 0; // Show all the key-value pairs, looking for the the key nodeId from the form data posted up foreach (var key in provider.FormData.AllKeys) { foreach (var val in provider.FormData.GetValues(key)) { if (key.ToUpper() == "NODEID") { nodeId = Int32.Parse(val); // we need a clean, new assets folder, any pre-existing folder needs to be deleted as it's contents are now out of date // TO DO: in future we could zip up the old folder and date stamp it to allow roll backs. var assetFolder = HttpContext.Current.Server.MapPath(baseUploadFolder + "/" + nodeId); var assetArchive = HttpContext.Current.Server.MapPath(baseUploadFolder + "/archive/" + nodeId); // if the archive folder doesn't exist, create it if (!Directory.Exists(assetArchive)) { Directory.CreateDirectory(assetArchive); } // if the asset folder exists, zip up the contents and put in the archive folder, // then delete the asset folder and recreate it, making it a clean folder if (Directory.Exists(assetFolder)) { // zip up contents and archive, e.g. SCORM-Assets/archive/1070/1070_20180123130522.zip ZipFile.CreateFromDirectory(assetFolder, assetArchive + "/" + nodeId + "_" + DateTime.UtcNow.ToString("yyyyMMddHHmmss") + ".zip"); Directory.Delete(assetFolder, true); Directory.CreateDirectory(assetFolder); } else // first time this asset has been uploaded, so create a folder for it { Directory.CreateDirectory(assetFolder); } // find the destination zip file path var destZipFile = Path.Combine(assetFolder, fileName); // move new asset from user upload folder, into asset folder File.Copy(Path.Combine(userUploadFolder, fileName), destZipFile, true); // delete old upload folder Directory.Delete(userUploadFolder, true); // extract new asset zip into folder using (ZipArchive archive = ZipFile.Open(destZipFile, ZipArchiveMode.Read)) { archive.ExtractToDirectory(assetFolder); } // delete uploaded zip as it's not needed anymore File.Delete(destZipFile); var status = PopulateAssetUrlProperty(nodeId, userId, assetFolder); if (status.StatusType == PublishStatusType.Success || status.StatusType == PublishStatusType.SuccessAlreadyPublished) { response = Request.CreateResponse(HttpStatusCode.Created); response.Content = new StringContent(fileName); return(response); } else { response = Request.CreateResponse(HttpStatusCode.Conflict); response.Content = new StringContent(fileName); return(response); } } } } response = Request.CreateResponse(HttpStatusCode.BadRequest); return(response); }
// GET api/<controller>/Add/5 public ProductSummary Post([FromBody] ProductAdd product) { int qty = product.quantity; string productId = product.productId; ProductSummary summary = new ProductSummary { Status = false }; if (string.IsNullOrEmpty(productId)) { return(summary); } if (qty < 1) { return(summary); } HttpContextBase abstractContext = new System.Web.HttpContextWrapper(HttpContext.Current); string visitorId = session.getUser(abstractContext.Session); Basket existingItem = db.Baskets.Where(b => b.VisitorId == visitorId && b.ProductId == productId).FirstOrDefault(); if (existingItem != null) { existingItem.Quantity += qty; try { db.Entry(existingItem).State = EntityState.Modified; db.SaveChanges(); } catch (Exception) { return(summary); } } else { Basket basket = new Basket { BasketId = Guid.NewGuid(), VisitorId = visitorId, Quantity = qty, ProductId = productId, CreatedDate = DateTime.UtcNow }; try { db.Baskets.Add(basket); db.SaveChanges(); } catch (Exception) { return(summary); } } List <Basket> basketItems = store.GetBasketItems(visitorId, db); int countItems = basketItems.Sum(a => a.Quantity); summary.Status = true; summary.Quantity = countItems; return(summary); }
public override ISubscriptionToken AddOnSendingHeaders(Action <HttpContextBase> callback) { return(_httpResponse.AddOnSendingHeaders(HttpContextWrapper.WrapCallback(callback))); }
/// <summary> /// </summary> /// <param name="httpContextWrapper"> </param> public MvcContext(System.Web.HttpContextWrapper httpContextWrapper) { InitializeContext(httpContextWrapper); }
public static string SendChallanEmail(DataTable dtChallanDtl, System.Web.HttpContextWrapper ctx = null) { string Msg = ""; string ErrorMsg = ""; string MailSubject = ""; StringBuilder strMessage = new StringBuilder(); string challanId = ""; try { string GmailUserNameKey = System.Web.Configuration.WebConfigurationManager.AppSettings["GmailUserNameKey"].ToString(); string GmailPasswordKey = System.Web.Configuration.WebConfigurationManager.AppSettings["GmailPasswordKey"].ToString(); string GmailHostKey = System.Web.Configuration.WebConfigurationManager.AppSettings["GmailHostKey"].ToString(); string GmailPortKey = System.Web.Configuration.WebConfigurationManager.AppSettings["GmailPortKey"].ToString(); string GmailSslKey = System.Web.Configuration.WebConfigurationManager.AppSettings["GmailSslKey"].ToString(); string TestEmail = System.Web.Configuration.WebConfigurationManager.AppSettings["TestEmail"].ToString(); string EmailIdTo = System.Web.Configuration.WebConfigurationManager.AppSettings["TestEmailId"].ToString(); SmtpClient smtp = new SmtpClient(); smtp.Host = GmailHostKey; smtp.Port = Convert.ToInt16(GmailPortKey); smtp.EnableSsl = Convert.ToBoolean(GmailSslKey); smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential(GmailUserNameKey, GmailPasswordKey); try { //challanId = Convert.ToInt32(ChallanIds[i]).ToString(); //DataTable dtChallanDtl = objDbTrx.GetChallanPrintDetailsById(Convert.ToInt64(challanId)); if (dtChallanDtl.Rows.Count > 0) { if (TestEmail.ToUpper() == "FALSE") { EmailIdTo = dtChallanDtl.Rows[0]["EMAIL_ID"].ToString(); } strMessage = new StringBuilder(); MailSubject = "Chargeble Challan no.: " + dtChallanDtl.Rows[0]["CHALLAN_NUMBER"].ToString() + " Date : " + Convert.ToDateTime(dtChallanDtl.Rows[0]["CHALLAN_DATE"]).ToString("dd-MMM-yyyy"); strMessage.AppendLine(" <table id='InvoiceCumChallanReport' cellpadding='0' cellspacing='0' border='1' width='100%'>"); strMessage.AppendLine("<tr><td colspan='7'><b>PRINTING & DELIVERY OF 'NTB:</b></td></tr>"); strMessage.AppendLine("<tr>"); strMessage.AppendLine(" <td colspan='3'>Chargeble Challan no.: <b>" + dtChallanDtl.Rows[0]["CHALLAN_NUMBER"].ToString() + "</b></td>"); strMessage.AppendLine(" <td colspan='4' style='text-align:left;'><b>Date : " + Convert.ToDateTime(dtChallanDtl.Rows[0]["CHALLAN_DATE"]).ToString("dd-MMM-yyyy") + "</b></td>"); strMessage.AppendLine("</tr>"); strMessage.AppendLine("<tr>"); strMessage.AppendLine(" <td style='text-align:left;font-size:small;'>Transporter Name</td>"); strMessage.AppendLine(" <td style='text-align:left;font-size:small;'>" + dtChallanDtl.Rows[0]["Transport_Name"].ToString() + "</td>"); strMessage.AppendLine(" <td style='text-align:left;font-size:small;'>Consignment No.</td>"); strMessage.AppendLine(" <td style='text-align:left;font-size:small;'>" + dtChallanDtl.Rows[0]["CONSIGNEE_NO"].ToString() + "</td>"); strMessage.AppendLine(" <td style='text-align:left;font-size:small;'>Truck No.</td>"); strMessage.AppendLine(" <td style='text-align:left;font-size:small;' colspan='2'>" + dtChallanDtl.Rows[0]["VEHICLE_NO"].ToString() + "</td>"); strMessage.AppendLine("</tr>"); strMessage.AppendLine("<tr>"); strMessage.AppendLine(" <td style='vertical-align:bottom;text-align:left;font-size:small;width:18%;'><b>Class</b></td>"); strMessage.AppendLine(" <td style='vertical-align:bottom;text-align:left;font-size:small;width:18%;'><b>Book Code</b></td>"); strMessage.AppendLine(" <td style='vertical-align:bottom;text-align:left;font-size:small;width:18%;'><b>Name of the Books/Forms</b></td>"); strMessage.AppendLine(" <td style='vertical-align:bottom;text-align:left;font-size:small;width:18%;'><b>Quantity Delivered</b></td>"); strMessage.AppendLine(" <td style='vertical-align:bottom;text-align:left;font-size:small;width:18%;'><b>Unit</b></td>"); strMessage.AppendLine(" <td style='vertical-align:bottom;text-align:left;font-size:small;width:18%;'><b>No. of Box <br />bundle/ cartoon/ pack</b></td>"); strMessage.AppendLine(" <td style='vertical-align:bottom;text-align:left;font-size:small;width:18%;'><b>Remarks (if any)</b></td>"); strMessage.AppendLine("</tr>"); for (int iCnt = 0; iCnt < dtChallanDtl.Rows.Count; iCnt++) { strMessage.AppendLine("<tr>"); strMessage.AppendLine(" <td style='text-align:left;'>" + dtChallanDtl.Rows[iCnt]["CLASS"].ToString() + "</td>"); strMessage.AppendLine(" <td style='text-align:left;'>" + dtChallanDtl.Rows[iCnt]["BOOK_CODE"].ToString() + "</td>"); strMessage.AppendLine(" <td style='text-align:left;'>" + dtChallanDtl.Rows[iCnt]["BOOK_NAME"].ToString() + "</td>"); strMessage.AppendLine(" <td style='text-align:left;'>" + dtChallanDtl.Rows[iCnt]["QtyShippedQty"].ToString() + "</td>"); strMessage.AppendLine(" <td style='text-align:left;'>Copies</td>"); strMessage.AppendLine(" <td style='text-align:left;'>" + dtChallanDtl.Rows[iCnt]["Cartoon"].ToString() + "</td>"); strMessage.AppendLine(" <td style='text-align:left;'>" + dtChallanDtl.Rows[iCnt]["Remarks"].ToString() + "</td>"); strMessage.AppendLine("</tr>"); } strMessage.AppendLine("</table>"); using (var message = new MailMessage(GmailUserNameKey, EmailIdTo)) { message.Subject = MailSubject; message.Body = strMessage.ToString(); message.IsBodyHtml = true; smtp.Send(message); } } } catch (Exception ex) { ErrorMsg += ErrorMsg + " " + ex; } if (ErrorMsg == "") { ErrorMsg = "Email sent"; } } catch (Exception ex) { ErrorMsg = "Some error occoured while sending email. " + ex.Message + ". " + ex.InnerException; } return(ErrorMsg); }
public HomeController() { var cont = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current); Auth = new OwinAuth(cont as HttpContextBase); }
private string GetStores(double lat, double lng) { Uri uri = HttpContext.Current.Request.Url; String host = uri.Scheme + Uri.SchemeDelimiter + uri.Host; if (!uri.Port.Equals(String.Empty)) { host += ":" + uri.Port; } StringBuilder requestUrl = new StringBuilder(); requestUrl.Append(host); requestUrl.Append("/sitefinity/frontend/services/DynamicModules/Data.svc/live/?"); requestUrl.Append("provider="); requestUrl.Append("&itemType=Telerik.Sitefinity.DynamicTypes.Model.Stores.Store"); requestUrl.Append("&radius=150"); requestUrl.Append("&latitude="); requestUrl.Append(lat); requestUrl.Append("&longitude="); requestUrl.Append(lng); requestUrl.Append("&geoLocationProperty=address"); requestUrl.Append("&sortExpression=Distance%20ASC"); if (SecurityManager.GetCurrentUserName().Equals("Anonymous")) { SecurityManager.AuthenticateUser("Default", visitorUsername, visitorPassword, true); } var abstractContext = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current); SecurityManager.UpdateCookies(abstractContext); var cookieCollection = abstractContext.Response.Cookies; HttpWebRequest getStores = (HttpWebRequest)WebRequest.Create(requestUrl.ToString()); CookieContainer cookieJar = new CookieContainer(); foreach (string cookieKey in cookieCollection.AllKeys) { HttpCookie oCookie = cookieCollection.Get(cookieKey); Cookie oC = new Cookie(); oC.Domain = uri.Host; oC.Expires = oCookie.Expires; oC.Name = oCookie.Name; oC.Path = oCookie.Path; oC.Secure = oCookie.Secure; oC.Value = oCookie.Value; cookieJar.Add(oC); } getStores.CookieContainer = cookieJar; getStores.Method = "GET"; HttpWebResponse response = (HttpWebResponse)getStores.GetResponse(); using (Stream stream = response.GetResponseStream()) { string storesResponse = new StreamReader(stream).ReadToEnd(); if (SecurityManager.GetCurrentUserName().Equals(visitorUsername)) { SecurityManager.Logout(); SecurityManager.DeleteAuthCookies(); } return(storesResponse); } }