Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I've the following code:

    protected Dictionary<NpInfoHelper, object> Informer;
    protected override void OnInit(EventArgs e)
    {
        if (Session.Keys.Count == 1)
        {
            Session.Abandon();
            Response.RedirectPermanent("~/Pages/Login?e=true", true);
        }
        else
        {
            Informer = (Dictionary<NpInfoHelper, object>)Session["Informer"];
        }
        base.OnInit(e);
    }

in every backend .cs file of the .aspx file.

I think this is repetitive. Note that I'll be using Informer in every .aspx.cs file.

The above code is repeated 19 times. Can I make it just one?

share|improve this question
3  
Well, I can't say much about ASP.NET, but that kind of repetition implies you should either have the backend classes all derive from one class (whose OnItit does what your init does above). –  Travis Snoozy Apr 27 at 4:47

1 Answer 1

up vote 7 down vote accepted

Per the comment, what you probably want is an abstract class MyAppPage:

abstract class MyAppPage : Page {
    protected Dictionary<NpInfoHelper, object> Informer;
    protected override void OnInit(EventArgs e)
    {
        if (Session.Keys.Count == 1)
        {
            Session.Abandon();
            Response.Redirect("~/Pages/Login?e=true", true);
        }
        else
        {
            Informer = (Dictionary<NpInfoHelper, object>)Session["Informer"];
        }
        base.OnInit(e);
    }
}

then your other pages would extend MyAppPage instead of Page.

Finally, you'll notice I took the liberty of changes Response.RedirectPermanent to Response.Redirect. Permanent redirections return the 301 response "Moved Permanently" and signify that the current page no longer exists at this position and has been moved elsewhere. Using it to redirect someone who hasn't logged in might confuse crawlers.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.