Referencing web controls from c# not on code behind

I need assistance, I am not sure what to ask...
namespace WebApplication1.Debug
{
    public partial class TreeView : System.Web.UI.Page
    {
        string RequestingPage = "Lucid: " + HttpContext.Current.Request.PhysicalApplicationPath + HttpContext.Current.Request.CurrentExecutionFilePath; //New2015_0423_1033!

        Boolean DebugFlag; //default bool = false, 0

        protected void Page_Load(object sender, EventArgs e)
        {
if (!IsPostBack) // INITIAL LOAD ONLY
            {
                SessionLog StatusLog = new SessionLog();
                if (Session["StatusLog"] == null)
                {
                    Session["StatusLog"] = "Initialized";
                }
                txtStatusLog.Text = StatusLog.StatusLogUpdate(BLogic.ConnectStringName, DebugFlag, "Debug");
                divDebug.Visible = true; //hide debug division
                DebugFlag = true;
                string HostName = System.Environment.GetEnvironmentVariable("COMPUTERNAME");
                if (ddlUID.SelectedValue != null) { UID = ddlUID.SelectedValue; }
            )

Open in new window


This code (significantly shortened) is currently pasted at the top of every webpage in our project.  The issue is whenever anything changes in this code I got about ~50 places to edit, not maintainable!  I want to move it off the pages (into its own class?) and just have a few lines on each page to implement.  All my attempts, the main problem is referencing the controls on each page.  I think I need to use inheritance or something.  Being new to OOP I have not been able to have one universal piece of code to set/get properties on various webpages.  Please also help me ask the right question.  

Kind Regards
Sam
SamCashAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

dejaanbuCommented:
are you using masterpage ?
If i understand correctly,
are you repeating the txtStatusLog, divDebug, ddlUID in all webforms?
if yes, consider about having them all in a masterpage, and in masterpage_load u can have all those code.
SamCashAuthor Commented:
Dejaanbu,

I like the idea of putting it all on the masterpage, I will just have one copy...

Yes I am using a masterpage.  Yes, txtStatusLog, divDebug, ddlUID in all webforms.  I also have some page variables, UserID, EntityID, RequestingPage, except for RequestingPage they are also on all pages.

On the childpage how do I reference(scope) a TextBox on the masterpage in the codebehind  of a childpage?  See snipet below, notice myChildPage which is a childpage codebehind trying to get a value from a text box on the masterpage.  Can I do this? How?

namespace WebApplication1.Debug
{
    public partial class myChildPage: System.Web.UI.Page

string s = txtBoxOnMasterPage.Text

Open in new window



Regards
Sam
dejaanbuCommented:
Use the FindControl method, using the value returned by the Master property as the naming container.

More details here:
https://msdn.microsoft.com/en-us/library/xxwa0ff0%28v=vs.140%29.aspx
http://www.4guysfromrolla.com/articles/013107-1.aspx
SamCashAuthor Commented:
Dejaanbu,

Thanks, I read the article from 4Guys.  I am still digesting, have Friday off, will be back to this on Tuesday.  I wonder if this technique will interface the MasterPage with the webforms in the Iframes

The structure I am working in:

1. MasterPage.aspx
2.      default.aspx
3.          36 (and growing) Iframes each containing 1 webform.aspx 
            each has a codebehind, webform.aspx.cs - mostly GUI stuff
4.                   one Class for Business Logic and utilities, BLogic.cs, which is shared by all webforms.aspx.cs

Open in new window


Currently each webform.aspx requires 174 (and growing) lines of code which I want to move to 1 maintainable file.

Thank you for your assistance with the architecture and design of this system.
Sam

namespace WebApplication1.Debug
{
    public partial class TreeView : System.Web.UI.Page
    {
        string RequestingPage = "Lucid: " + HttpContext.Current.Request.PhysicalApplicationPath + HttpContext.Current.Request.CurrentExecutionFilePath; //New2015_0423_1033!

        //SessionLog StatusLog = new SessionLog(); //Try Singleton Object
        Boolean DebugFlag; //default bool = false, 0

        string UID, AID, LID, FID;
        string Username;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) // INITIAL LOAD ONLY
            {
                SessionLog StatusLog = new SessionLog();
                if (Session["StatusLog"] == null)
                {
                    Session["StatusLog"] = "Initialized";
                }
                txtStatusLog.Text = StatusLog.StatusLogUpdate(BLogic.ConnectStringName, DebugFlag, "Debug");

#if DEBUG //set defaults for development - DEBUG

                //bodyMain.Attributes.Add("onLoad", "detectIframe();"); //Force to load inside Iframe by redirecting to "/default.aspx"

                //Test weather Brian or Tony's box... System.Environment.MachineName;
                divDebug.Visible = true; //hide debug division
                DebugFlag = true;
                string HostName = System.Environment.GetEnvironmentVariable("COMPUTERNAME");
                if (HostName == "LENOVO-TONY")
                {
                    if (BLogic.ConnectStringName == "HW_LocalSQL") //LOCAL
                    {
                        UID = "190";
                        AID = "193"; string used = AID; // "used" to get rid of not used warnings
                        LID = "196";
                    }
                    else if (BLogic.ConnectStringName == "HW_orodevSQL") // .205
                    {
                        UID = "65";
                        AID = "2";
                        LID = "239";
                    }
                    else if(BLogic.ConnectStringName == "NSA_orodevSQL") //.200
                    {
                        UID = "24";
                        AID = "2";
                        LID = "7862"; // Test4
                    }
                    else
                    {
                        throw new ArgumentException("Unidentified ConnectionStringName.");
                    }
                }
                else //assume "Brian"
                {
                    UID = "1";
                    AID = "2";
                    LID = "3";
                }

                PopulateDebugDdls();
                
#endif
#if !DEBUG //RELEASE -- sb !DEBUG
                // if Local Host, assume "Release" debugging, set vaiables

                string HostName = System.Environment.GetEnvironmentVariable("COMPUTERNAME");
                if (HostName == "LENOVO-TONY")
                {
                    if (BLogic.ConnectStringName == "HW_LocalSQL") //LOCAL
                    {
                        UID = "190";
                        AID = "193"; string used = AID; // "used" to get rid of not used warnings
                        LID = "196";
                    }
                    else if (BLogic.ConnectStringName == "HW_orodevSQL") // .205
                    {
                        UID = "65";
                        AID = "2";
                        LID = "239";
                    }
                    else if(BLogic.ConnectStringName == "NSA_orodevSQL") //.200
                    {
                        UID = "24";
                        AID = "2";
                        LID = "7862"; // Test4
                    }
                    else
                    {
                        throw new ArgumentException("Unidentified ConnectionStringName.");
                    }
                
                divDebug.Visible = true; //hide debug division for release
                ddlUID.Visible = true;
                ddlLeagueID.Visible = true;
                PopulateDebugDdls();

                DebugFlag = true; //hide for release
                txtStatusLog.Text = StatusLog.StatusLogUpdate("Relaese LocalHost", DebugFlag, "Debug");
                
                }
                else //Not Local Host
                {
                    bodyMain.Attributes.Add("onLoad", "detectIframe();"); //Force to load inside Iframe by redirecting to "/default.aspx"

                    divDebug.Visible = false; //hide debug division for release
                    ddlUID.Visible = false;
                    ddlLeagueID.Visible = false;

                    DebugFlag = false; //hide for release

                    //get UID, AID, LID from session, url, and database
                    UID = (string)(Session["UserContactID"]); // from session set to "nnn" to pretest Relase build
                    Username = Server.HtmlEncode(User.Identity.Name);

                    string appPath = Request.ApplicationPath;
                    string LeagueURL = appPath.Substring(appPath.LastIndexOf('/') + 1); //
                    if (LeagueURL != null && LeagueURL != "")
                    {
                        LID = Convert.ToString(BLogic.LeagueIDByUrlGet(LeagueURL, RequestingPage));
                    }
                    DebugFlag = false; //hide for release
                    txtStatusLog.Text = StatusLog.StatusLogUpdate("Release Not LocalHost", DebugFlag, "Debug");
                }
#endif
                if (UID == null
                    || UID == ""
                    || LID == null // if root then qualify AID instead of LID
                    || LID == "")
                {
                    txtStatusLog.Text = StatusLog.StatusLogUpdate("Must have a valid UID and LID", DebugFlag, "Debug"); //appends this message to top of status log

                    UID = "0"; // setting these to "0" prevents sql exceptions during PopulatePage();
                    AID = "0";
                    LID = "0";
                }
                AID = "2";  // get this programmatically
                PopulatePage();
            }
            else // ONLY ON POST BACK 
            {
                //Get Page Variables on postback

//#if !DEBUG
                //DebugFlag = false;
                //get UID, AID, LID from session, url, and database
                UID = (string)(Session["UserContactID"]); // from session set UID = "190" to pretest Release build

                string appPath = Request.ApplicationPath;
                string LeagueURL = appPath.Substring(appPath.LastIndexOf('/') + 1); //set LeagueURL = "bravesleague" to pretest Release build;
                if (LeagueURL != null && LeagueURL != "")
                {
                    LID = Convert.ToString(BLogic.LeagueIDByUrlGet(LeagueURL, RequestingPage)); //Get LID from database
                }

//#endif
                if (ddlUID.SelectedValue != null) { UID = ddlUID.SelectedValue; } // null if in Release and ! localhost
                AID = "2"; // or 193 for local
                if (ddlLeagueID.SelectedValue != null) { LID = ddlLeagueID.SelectedValue; } // null if in Release and ! localhost

                if (UID == null
                    || UID == ""
                    || LID == null // if root then qualify AID instead of LID
                    || LID == "")
                {
                    SessionLog StatusLog = new SessionLog();
                    txtStatusLog.Text =  StatusLog.StatusLogUpdate("Must have a valid UID and LID 2", DebugFlag, "Debug");
                    
                    //Response.Redirect(Request.Url.AbsoluteUri, true); //Solution make non null parameters, probally string = "0" for uid,aid, lid, pop page with nothing
                    //return; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& this does not work!
                }
            
            }
        }

Open in new window

dejaanbuCommented:
it is cumbersome to analyze and suggest the maintainable code, as i am not aware of the purpose of the project/module.

start with little changes, for ex, in masterpage add a textbox(txtStatusLog) and try to access that in ur client page's load event. on success, go with the other controls/public members. I agree, it is hard to optimize 174 lines in all pages, but the truth is, it takes time...

Good luck with ur optimization.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.