Custom Routes with kentico Portal Template - asp.net

Asp.net allows us to register new custom routes
http://www.example.com/products.aspx?category=software
to call them like that : http://www.example.com/products/software
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
static void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("testroute", "Test/{parame}", "~/Default.aspx");
}
This method works in Kentico but only for .aspx pages (for example for pages in ~/CMSPages/Default.aspx).
My question is how to achive same results for pages created with Portal Template approach?
I was trying to make my own HttpHandler
public class CustomHandlerProduct : IHttpHandler
{
public CustomHandlerProduct()
{
//
// TODO: Add constructor logic here
//
}
public bool IsReusable
{
// To enable pooling, return true here.
// This keeps the handler in memory.
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
}
}
or even HttpModule according to this article
link to CodeProject article
but i can not achive desired results
any Ideas?

If you want to use Portal engine, is there a reason not to use Kentico URL rewriting capabilities? Wildcard URLs work very similarly to routes. See the documentation https://docs.kentico.com/display/K82/Wildcard+URLs

Related

OnAppearing not called in prism xamarin forms

I want a process to be called each time I navigated to my view to refresh a list.
I am using Xamarin Forms and prism framework.
I made my ViewModel derivate from ContentPage but the following method is never called :
protected override void OnAppearing()
{
//Do things
}
How am I supposed to do to get the event? Is it better to use OnNavigateTo?
Through the document:
There are times in your application where you may want to invoke code
in your ViewModel based on when the Page Appears or Disappears without
Navigation specific consideration. For these times you can utilize the
IPageLifecycleAware interface to properly respond to the Appearing and
Disappearing events from the Page.
public class ViewAViewModel : IPageLifecycleAware
{
public void OnAppearing()
{
Console.WriteLine("We are appearing");
}
public void OnDisappearing()
{
Console.WriteLine("We are disappearing");
}
}
I found a solution to make my code work, I add to do this in my code behind from the page:
protected override void OnAppearing()
{
(BindingContext as IPageLifecycleAware)?.OnAppearing();
}
Still a mystery why I need to add this and it is not in the sample.
at the time of this post, the sample does it differently. It uses Behaviors to achieve expectation
It has a PageLifeCycleAwareBehavior class
private void OnAppearing(object sender, EventArgs e)
{
MvvmHelpers.InvokeViewAndViewModelAction<IPageLifecycleAware>(AssociatedObject, aware => aware.OnAppearing());
}
private void OnDisappearing(object sender, EventArgs e)
{
MvvmHelpers.InvokeViewAndViewModelAction<IPageLifecycleAware>(AssociatedObject, aware => aware.OnDisappearing());
}
You can see the full implementation here
You can also call Initialize is a good alternative
Add ini to your class
public class HelloViewModel : BindableBase, IInitialize
then add the following method
public void Initialize(INavigationParameters parameters)
{
// Do stuff
}

HttpModule endless redirect

I'm using an HttpModule to try and redirect users to the login page if they're not authenticated, but for some reason it's just endlessly redirecting the page without landing anywhere.
Here's the module:
using System;
using System.Web;
using System.Web.Security;
public class AuthenticationModule : IHttpModule
{
public AuthenticationModule()
{
}
public string ModuleName
{
get
{
return "AuthenticationModule";
}
}
public void Init(HttpApplication app)
{
app.BeginRequest += (new EventHandler(Application_BeginRequest));
}
private void Application_BeginRequest(object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;
HttpRequest request = context.Request;
HttpResponse response = context.Response;
if (!request.IsAuthenticated && !request.RawUrl.Contains(FormsAuthentication.LoginUrl))
{
FormsAuthentication.RedirectToLoginPage();
}
}
public void Dispose() { }
}
I don't recall having ever worked with HttpModules before, so I'm not sure what's not working.
How can I fix this?
request.RawUrl is the URL I entered into the browser. Your check request.RawUrl.Contains(FormsAuthentication.LoginUrl) is case sensitive.
Additionally there are no checks for ressources. So each request for images, css files etc. will redirect to login page. You need to check if authentication is required for the ressource being called.
Edit (hit the save button to early)
Additionally I would do it on AuthenticateRequest

Is there any built in Events in asp.net which triggers for all PageLoads?

After Completing My asp Project I came up with a new requirement. For this, I have to Execute some code in all page Load events. Can I get an event for all those page loads? I can't use Session_start of Global.asax since it will include WebHandlers with Session State. Any Ideas?
You keep a Base Page and Inherit it from all aspx pages. In this way you can keep the logic centralized.
Example
Aspx Page
public partial class MyAspxPage : BasePage
{
}
Base Page
public class BasePage : Page
{
protected override void OnLoad(EventArgs e)
{
}
}
You should also leave AutoEventWireup set to false.
Session start would not be suitable as it will only be fired when a users is given a new session rather than each time a page is loaded.
There are several options, including using a base page which all of you pages inherit from. This will mean you need to remember to hook this up to all pages.
My suggestion would be to write an http module which is fired for all aspx page loads.
You will need to create a module which implements System.Web.IHttpModule.
using System;
using System.Web;
public class HelloWorldModule : IHttpModule
{
public HelloWorldModule()
{
}
public String ModuleName
{
get { return "HelloWorldModule"; }
}
// In the Init function, register for HttpApplication
// events by adding your handlers.
public void Init(HttpApplication application)
{
application.BeginRequest +=
(new EventHandler(this.Application_BeginRequest));
application.EndRequest +=
(new EventHandler(this.Application_EndRequest));
}
private void Application_BeginRequest(Object source,
EventArgs e)
{
// Create HttpApplication and HttpContext objects to access
// request and response properties.
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
string filePath = context.Request.FilePath;
string fileExtension =
VirtualPathUtility.GetExtension(filePath);
if (fileExtension.Equals(".aspx"))
{
context.Response.Write("<h1><font color=red>" +
"HelloWorldModule: Beginning of Request" +
"</font></h1><hr>");
}
}
public void Dispose() { }
}
Then hook it up in the web.config as per the example here.
<httpModules>
<add name="HelloWorldModule" type="HelloWorldModule" />
</httpModules>
You would need to check the context.Request.Path property in the module to exclude any request where the path did't meet your criteria (i.e. not ending aspx).
More info here.
https://web.archive.org/web/20200618051219/http://www.4guysfromrolla.com:80/demos/printPage.aspx?path=/articles/011404-1.aspx
I think the best solution here whould be to create a custom base page class which implements PageLoad and then inherit all your pages from it.
Something like:
public abstract class BasePage: Page
{
protected void Page_Load(object sender, EventArgs e) {
// your code
}
}
You can register base page class in web.config:
<system.web>
<!-- ... -->
<pages pageBaseType="MyWeb.UI.BasePage" />
<!-- ... -->
</system.web>

Custom HTTP handler for URL rewriting + session and application variable

Currently my product page URL is like
http://www.localhost:80/products/default.aspx?code=productCode
I want to access product page with
http://www.localhost:80/productCode
I have used HTTP module for this.
public class UrlRewritingModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
context.AuthorizeRequest += new EventHandler(context_AuthorizeRequest);
}
void context_AuthorizeRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
if (some condition)
{
context.RewritePath(url);
}
}
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
//We set back the original url on browser
HttpContext context = ((HttpApplication)sender).Context;
if (context.Items["originalUrl"] != null)
{
context.RewritePath((string)context.Items["originalUrl"]);
}
}
}
I have register it in web.config and it is working fine. But when I deploy it in IIS that session and application variables are not throwing null referent Exceptions.
Can anyone help me?
Edit: Do it require extra code to access session/ Application variable for rewritten URLs
?
Have you tried using HTTPContext.Current?
I was able to solve issue (accessing session and application variables in subsequent pages rewritten by custom handler) by adding runAllManagedModulesForAllRequests="true" attribute in modules in web.config.

Using HttpModules to modify the response sent to the client

I have two production websites that have similar content. One of these websites needs to be indexed by search engines and the other shouldn't. Is there a way of adding content to the response given to the client using the HttpModule?
In my case, I need the HttpModule to add to the response sent to the when the module is active on that particular web.
You'd probably want to handle the PreRequestHandlerExecute event of the application as it is run just before the IHttpHandler processes the page itself:
public class NoIndexHttpModule : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += AttachNoIndexMeta;
}
private void AttachNoIndexMeta(object sender, EventArgs e)
{
var page = HttpContext.Current.CurrentHandler as Page;
if (page != null && page.Header != null)
{
page.Header.Controls.Add(new LiteralControl("<meta name=\"robots\" value=\"noindex, follow\" />"));
}
}
}
The other way of doing it, is to create your own Stream implementation and apply it through Response.Filters, but that's certainly trickier.

Resources