Jamie
Jamie

Reputation: 1679

Add code in page base to header C#

I have the following code in my MasterPageBase.cs file:

        protected override void OnLoad(EventArgs e)
    {
        string url = Request.Path;
        var page = _ContentPageRepository.GetContentPageByUrl(url, ConfigurationManager.GetSiteID());
        if (page != null)
        {
            PageBase.SetTitle(page.Title);
            PageBase.SetDescription(page.Description);
            PageBase.SetKeywords(page.Keywords);
        }
        else
        {
            this.ProcessSiteMap();
        }

        this.AddGACode(); 
        base.OnLoad(e); 
    }

I need this.AddGACode(); to get added to the head section of the page, but when I view the source of the page as I am running the solution, I see that this is adding it to the body section of the page.

I have tried Page.Header.Controls.Add(AddGACode()); and get the following errors: The best overloaded method match has some invalid arguments and cannot convert from 'void' to 'System.Web.UI.Control'

What can I do to get this code added to the head? TIA

EDIT: Request to see the AddGACode method:

        private void AddGACode()
    {
        var gaCode = SiteManager.GetSite().GoogleAnalyticsCode;
        if (!String.IsNullOrEmpty(gaCode) && Response.StatusCode == 200)
        {
            if (!ConfigurationManager.EnableUniversalGATracking)
            {
                ClientScriptManager cs = Page.ClientScript;
                StringBuilder csText = new StringBuilder();
                csText.Append("<script type=\"text/javascript\">");
                csText.Append(String.Format("var _gaq = _gaq || []; _gaq.push(['_setAccount', '{0}']); ", gaCode));
                csText.Append("_gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();");
                csText.Append("</script>");
                cs.RegisterClientScriptBlock(GetType(), "GACode", csText.ToString());
            }
            else
            {
                ClientScriptManager cs = Page.ClientScript;
                StringBuilder csText = new StringBuilder();
                csText.Append("<!-- Universal GA Code --><script type=\"text/javascript\">");
                csText.Append(String.Concat("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '", gaCode,  " ', 'auto'); ga('send', 'pageview');"));
                csText.Append("</script>");
                cs.RegisterClientScriptBlock(GetType(), "GACode", csText.ToString());
            }
        }
    }

EDIT:

This code is in the AddGACode method. There is still this.AddGACode(); in the OnLoad of the page that seems to duplicate the code with this edit, but both codes will disappear if I delete this.AddGACode(); from OnLoad

ClientScriptManager cs = Page.ClientScript;
StringBuilder csText = new StringBuilder();
csText.Append("<!-- Universal GA Code --><script type=\"text/javascript\">");
csText.Append(String.Concat("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '", gaCode,  " ', 'auto'); ga('send', 'pageview');"));
csText.Append("</script>");
cs.RegisterClientScriptBlock(GetType(), "GACode", csText.ToString());
LiteralControl lc = new LiteralControl(csText.ToString());
Page.Header.Controls.Add(lc);

Upvotes: 0

Views: 1637

Answers (2)

MJVC
MJVC

Reputation: 507

This adds the script into the head tag:

        LiteralControl lt = new LiteralControl("<script type='text/javascript'>alert('test');</script>");
        Header.Controls.Add(lt);

UPDATE

LiteralControl lt = new LiteralControl(AddGACode());
Header.Controls.Add(lt);

...

private string AddGACode()
{
    var result = string.Empty;
    var gaCode = SiteManager.GetSite().GoogleAnalyticsCode;
    if (!String.IsNullOrEmpty(gaCode) && Response.StatusCode == 200)
    {
        StringBuilder csText = new StringBuilder();
        csText.Append("<script type=\"text/javascript\">");
        if (!ConfigurationManager.EnableUniversalGATracking)
        {
            csText.Append(String.Format("var _gaq = _gaq || []; _gaq.push(['_setAccount', '{0}']); ", gaCode));
            csText.Append("_gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();");
        }
        else
        {
            csText.Append(String.Concat("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '", gaCode,  " ', 'auto'); ga('send', 'pageview');"));
        }
        csText.Append("</script>");
        result = csText.ToString();
    }
    return result;
}

Upvotes: 1

Jon P
Jon P

Reputation: 19772

I'd keep your markup, in this instance your ga scripts, on mastpage itself. In the head tag add two literals, gaGaq and gaUniversal an then use you logic to contol the visibility of them.

<head runat="server"><script type="text\javascript">
       <asp:Literal id="gaGaq" runat="server">
             <!-- Put you gaq code here-->
             <!-- Keep {0} as a place holder for gaqCode -->
             </script>
       </asp:Literal>
       <asp:Literal id="gaUniveral" runat="server">
            <script type="text\javascrtip">
            <!-- Put you universal code here-->
            <!-- Keep {0} as a place holder for gaqCode -->
            </script>
       </asp:Literal>
</head>

C#

private void AddGACode()
{
    var gaCode = SiteManager.GetSite().GoogleAnalyticsCode;
    if (!String.IsNullOrEmpty(gaCode) && Response.StatusCode == 200)
    {
        if(ConfigurationManager.EnableUniversalGATracking)
        {   
            //Set gaCode
            gaUniversal.Text = string.Fomat(gaUniveral.Text, gaCode);
        }
        else
        {  
            //Set gaCode             
            gaGaq.Text = string.Format(ga.Text, gaCode);
        }

        gaUniversal.Visible = ConfigurationManager.EnableUniversalGATracking;
        gaGaq.Visible = !ConfigurationManager.EnableUniversalGATracking;
    }
    else
    {
       //Hide Both literals if no gaCode
       gaUniversal.Visible = gaGaq.Visible = false;
    }
}

You could also look at putting all this into a custom control. If you're interested in taking that route I wrote a blog article on exactly that for the gaq style google analytics so I could drop it onto my many asp.net websites. The code in that article owuld need to be modified to suite your needs but should be enough to get you stared.

Upvotes: 0

Related Questions