HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Can my code be made into one?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
canmadeintoonecode

Problem

I've the following code:

protected Dictionary Informer;
    protected override void OnInit(EventArgs e)
    {
        if (Session.Keys.Count == 1)
        {
            Session.Abandon();
            Response.RedirectPermanent("~/Pages/Login?e=true", true);
        }
        else
        {
            Informer = (Dictionary)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?

Solution

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

abstract class MyAppPage : Page {
    protected Dictionary Informer;
    protected override void OnInit(EventArgs e)
    {
        if (Session.Keys.Count == 1)
        {
            Session.Abandon();
            Response.Redirect("~/Pages/Login?e=true", true);
        }
        else
        {
            Informer = (Dictionary)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.

Code Snippets

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);
    }
}

Context

StackExchange Code Review Q#48298, answer score: 7

Revisions (0)

No revisions yet.