Kentico Tapping into Page Level Events - events

We are creating webevents in a DB other than Kentico. These webevents are then used for enterprise reporting. I need to implement the same inside Kentico project.
Is there an event that can fire after the page has loaded so that i can create my web event with page name and user information if logged in.
I have also seen in the past that with events, the Request and Session objects are not available. However, HTTPContext.Current is available. I need the Request and Session objects.
We are using Kentico version 7.0.92 and have a portal template site.
Now, i don't want to use portal template page to create events since this code executes multiple times with each request for a page.
Basically, i am interested in the PageName, Session and Request objects.
I have looked around Kentico 7 documentation. Looks like we have CMSRequestEvents but haven't been able to find sample code.
Update:
Looks like the missing piece is CMSContext class. Now just trying to find the right event for CMSRequestEvents, where i have the Session object available.

I'd suggest modifying Kentico\CMS\Global.asax.cs in the following way:
public override void Init()
{
base.Init();
CMSRequestEvents.AcquireRequestState.After += AcquireRequestState_After;
}
void AcquireRequestState_After(object sender, EventArgs e)
{
// Do your stuff...
}
By that time the HttpContext.Current.Session should already be initialized. Page name can be retrieved from the HttpContext.Current.Request which should never be null.

Related

How to access session from a view in ASP .NET Core MVC 1.0

I am trying to access session data from inside a view.
Use Case: I'm storing status messages in the session that will be displayed at the top of the page. Currently I implemented this by using a DisplayMessages() function that sets some ViewData[....] properties and calling it at the beginning of every controller action.
Goal: I want to only set the status message once without needing additional code in the controller to display the messages on the next page load.
So I'm trying to access the messages that are stored in the session directly from the view.
So far I have tried the following:
Dependency Injection of an IHttpContextAccessor (doesn't seem to work anymore with ASP .NET Core MVC 1.0.0
Creating a static class to access the session, including the change from next() to next.invoke() suggested in the comment
This didn't work. I could access the HttpContext and Session.IsAvailable was true, but there was no data in the session.
The following should work in the view: Context.Session.TryGetValue
If you are using the SessionExtensions then Context.Session.GetString will work.
Injecting IHttpContextAccessor does work, but starting with ASP.NET Core 1.0.0 RC2, the IHttpContextAcessor is not registered by default, because it has significant performance overhead per request. See this GitHub announcement for more information.
Tratcher posted:
IHttpContextAccessor can be used to access the HttpContext for the current thread. However, maintaining this state has non-trivial performance costs so it has been removed from the default set of services.
Developers that depend on it can add it back as needed:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
But in your use case, I would suggest using a ViewComponent, which is a reusable piece of View with logic, that do not depend on a controller.
The documentation can be found here.
In your Views you would simply embed it with
#await Component.InvokeAsync("PriorityList", new { maxPriority = 2, isDone = false })
or
#Component.Invoke("PriorityList", new { maxPriority = 2, isDone = false })
for synchronous calls.

MiniProfiler with Web.API 2; is there a global magic request context object?

I'm trying to setup MiniProfiler on my web api site, and having a hard time getting MiniProfiler.Current to work.
I followed the directions at miniprofiler.com, and have the following in global.asax:
protected void Application_Start()
{
MiniProfilerEF6.Initialize();
// other setup
}
protected void Application_BeginRequest() {
// need to start one here in order to render out the UI
MiniProfiler.Start();
}
protected void Application_EndRequest() {
MiniProfiler.Stop();
}
This uses the default WebRequestProfilerProvider, which stores the actual profile object in HttpContext.Current.Items.
When I ask for MiniProfiler.Current, it looks to HttpContext.Current.
When I make a request for one of my web api URLs:
Application_BeginRequest creates the profiler, store it in HttpContext.Current
in a web api MessageHandler, I can see HttpContext.Current
in a web apu IActionFilter, HttpContext.Current is now null, and my attempt to MiniProfiler.Current.Step("controller:action") fails
my EF queries run from various services do not get recorded, as that miniprofiler hook relies MiniProfiler.Current, which relies on HttpContext.Current, which is null right now
Application_EndRequest fires, and HttpContext.Current is magically back, and so it wraps up the profiler and tells me how long it's been since the request began
I dug through the code, and I can create my own IProfileProvider, to store the profiler object somewhere more reliable than HttpContext.Current, but I don't know where that could be.
I spent a few hours trying things out, but couldn't find a workable solution. The problems:
the IProfileProvider is a global variable; all worker threads in either the MVC or Web API pipeline all have to use the same IProfileProvider
I can dig around in web api RequestContext.Properties to pull out the HttpContext for that request, but that doesn't really help because my IProfileProvider is global across the entire app; If I tell it to store the profile in HttpContext A, then any simultaneous requests for other HttpContexts are going to pollute the profile
I can't rely on any kind of threadstorage because of async/await re-using threads dynamically
I can't stick the profiler object in an Ninject binding with InRequestScope because InRequestScope doesn't seem to work with web api 2.1, but even if I could
everyone says HttpRequestMessage.Properties is the new HttpContext.Current.Items, but again, IProfileProvider is a global variable and I don't know of a way to ensure each request is looking at their version HttpRequestMessage. MiniProfiler.Current can be called from anywhere, so I guess a global IProfileProvider would have to somehow inspect the call stack to and find an HttpRequestMessage there? That sounds like madness.
I'm at a loss. What I really want is a special variable.
The process of putting the question together I figured it out. HttpContext.Current can get lost when you async/await things: Why is HttpContext.Current null after await?
I had to make the web.config change listed there, and adjusted my filters to use Miniprofiler.Current before any awaiting.
Also discussed at https://www.trycatchfail.com/2014/04/25/using-httpcontext-safely-after-async-in-asp-net-mvc-applications/

What's the best way to detect the start of a session (similar to Global.ashx's Session_Start) when using ServiceStack SessionFeature?

I've enabled Sessions support in service stack like:
container.Register<IRedisClientsManager>(c => container.Resolve<PooledRedisClientManager>());
container.Register<ICacheClient>(c => c.Resolve<IRedisClientsManager>().GetCacheClient());
container.Register<ISessionFactory>(c => new SessionFactory(c.Resolve<ICacheClient>()));
//RE: https://github.com/ServiceStack/ServiceStack/wiki/Sessions
Plugins.Add(new SessionFeature());
I see that ss-id and ss-pidd cookies are set upon visiting the site, however I would like to know when a session is started (i.e., first request from that user) so i can capture the incoming referrer url.
Using traditional asp.net sessions, i'd use Session_Start in Global, however this doesn't fire for me while using SS sessions.
Is there a good way to detect this session start event when using ServiceStack? I didn't find any reference in my queries online, or on the ServiceStack Sessions wiki.
There is currently no "Session Started" event in ServiceStack's Sessions feature, but there are some events on IAuthSession that might be useful to use instead, e.g:
public interface IAuthSession
{
...
void OnRegistered(IServiceBase registrationService);
void OnLogout(IServiceBase authService);
void OnAuthenticated(IServiceBase authService, IAuthSession session,
IOAuthTokens tokens, Dictionary<string, string> authInfo);
}
If you still would like to see an OnSessionStarted event request it as a feature in ServiceStack's GitHub issues (and include your use-case), so we can keep track of it.

IIS 7 Custom Error Page without Web.config

Is there any way to set a custom error page in IIS 7 without creating a web.config?
Unfortunately researching this particular topic has been very difficult because there are SO many articles on how to do it with a web.config. What I'm looking for is either buried beneath the 8 million results I don't want or it's not possible.
Yes, there is. It involves either subscribing to the Application_Error event in Global.asax or by writing a custom ErrorHandlerAttribute.
Darin already gave the correct answer, but I want to go into a little more depth.
In any ASP.NET application, given it is Web Forms, MVC, or raw ASP.NET, you can always use Application_Error Global.asax. If your ASP.NET application does not have a Global.asax, all you need to do is right-click your project in Solution Explorer, Add New Item, and choose Global Application Class. You should only have this option available if you don't already have one.
In your Global.asax, if you don't already see it, you can add Application_Error as shown below:
protected void Application_Error(object sender, EventArgs e) {
}
This will be called automatically by ASP.NET whenever there is an error. But as stated here, this is not perfect. Specifically:
An error handler that is defined in the Global.asax file will only
catch errors that occur during processing of requests by the ASP.NET
runtime. For example, it will catch the error if a user requests an
.aspx file that does not occur in your application. However, it does
not catch the error if a user requests a nonexistent .htm file. For
non-ASP.NET errors, you can create a custom handler in Internet
Information Services (IIS). The custom handler will also not be called
for server-level errors.
In Application_Error you can process the uncaught exception with Server.GetLastError(). This will provide you the Exception that was thrown, or null. I am not sure why this handler would be called if an exception didn't occur, but I believe that it is possible.
To redirect the user, use Response.Redirect(). Whatever you pass for the url is going to be sent directly to the browser without any further processing, so you can't use application-relative paths. To do that I would use this method in combination with VirtualPathUtility.ToAbsolute(). For example:
Response.Redirect( VirtualPathUtility.ToAbsolute( "~/Error.aspx" ) );
This redirect will be a 302 (temporary redirect) rather than a 301 (permanent), which is what you want in the case of handling errors. It's worth noting that this overload of Response.Redirect is the same as calling the overload Response.Redirect(url, endResponse: true). This method works by throwing an exception, which is not ideal in terms of performance. Instead, call Response.Redirect(url, false) immediately followed by Response.Complete​Request().
If you're using ASP.NET MVC, [HandleError] is also an option. Place this attribute on your Controller or on an Action within a controller. When this attribute is present, MVC will display the Error view, found in the ~/Views/Shared folder.
But you can make this even easier for yourself. You can automatically add this attribute to call Controllers in your project by creating a FilterConfig class in your project. Example:
public class FilterConfig {
public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new HandleErrorAttribute());
}
}
And then add FilterConfig.RegisterGlobalFilters( GlobalFilters.Filters ); to your Application_Start() in Global.asax.
You can read more about the HandleErrorAttribute at https://msdn.microsoft.com/en-us/library/system.web.mvc.handleerrorattribute(v=vs.118).aspx.
But as stated above, both of these methods will never cover absolutely all errors that can occur during the processing of your application. It's not possible to provide the best user experience for all possible errors without using Web.config or configuring IIS manually.

MVC3 + WIF - FederationResult missing "wctx"

I have an MVC3 app for which I want to implement claims support. My goal is as follows:
provide a SignIn link, which when clicked displays a popup window with username/password and Facebook/WindowsLive/Google etc. links
automatically redirect to my SignIn page when a protected controller is accessed e.g. /Order/Delete
I've set up the application and providers in AppFabricLabs.com and included the STS in my project. I've also created an implementation of IAuthorizationFilter so I can mark my controllers as [WifAuth] and successfully get the OnAuthorization method called. I've implemented the use-case where the visitor has not been authenticated like this:
private static void AuthenticateUser(AuthorizationContext context)
{
var fam = FederatedAuthentication.WSFederationAuthenticationModule;
var signIn = new SignInRequestMessage(new Uri(fam.Issuer), fam.Realm);
context.Result = new RedirectResult(signIn.WriteQueryString());
}
and successfully get AppFabricLabs page with my Identity Provider choices (haven't figured out how to customise that page). When I log in my returnUrl gets called so I land in a controller method /Home/FederationResult, however the form posted to me contains only wa and wresult fields but I need wctx to know where to send the user... I haven't been able to figure out why.
the wresult is an XML document that contains (amongst a bzillion other things) the name and e-mail address of the user logging in but sadly does not contain the url to which the user was headed.
have I failed to configure something or am I just off base? thoughts anyone?
e
Just specify a Context for the SignInRequestMessage:
signIn.Context = HttpContext.Current.Request.RawUrl;
The wctx parameter is included in every request/response and also part of the form posted finally to your site.

Resources