5
\$\begingroup\$

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?

\$\endgroup\$
1
  • 3
    \$\begingroup\$ 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). \$\endgroup\$ – Travis Snoozy Apr 27 '14 at 4:47
7
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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