Question

I'm using SharePoint 2007 and I would like to add the JS code for Google Analytics into the master page. I think a Delegate Control is the way to go, as we already have a Delegate Control in the Head section of the master page.

However, in this case there is a requirement to enable and disable the code per site, so would this still be the best approach?

I have put following code in .ascx file and writing in body tag instead of head tag.

protected override void Render(HtmlTextWriter writer) {
            //base.Render(writer);
            if (SPContext.Current != null) {
                SPFile file = SPContext.Current.File;
                if (file.Item != null) {
                    if (file.Item.Fields.ContainsField(KeywordKey) &&
                      file.Item[KeywordKey] != null &&
                      file.Item[KeywordKey].ToString() != string.Empty) {
                        writer.Write(string.Format(@"<META name=""keywords"" content=""{0}"">", file.Item[KeywordKey].ToString()));
                      }
                     if (file.Item.Fields.ContainsField(DescriptionKey) &&
                      file.Item[DescriptionKey] != null &&
                      file.Item[DescriptionKey].ToString() != string.Empty) {
                        writer.Write(string.Format(@"<META name=""description"" content=""{0}"">", file.Item[DescriptionKey].ToString()));
                     }


                }
            }
        }

i would like to write meta keywords on head section instead of body tags.

Thanks Ronak

Here's the Elements.xml

<?xml version="1.0" encoding="utf-8" ?> 
<Elements xmlns="schemas.microsoft.com/sharepoint/">; 
<!-- Use a sequence number lower than default of 100, so the custom control gets loaded before SharePoint controls --> 
<Control Id="AdditionalPageHead" Sequence="50" ControlSrc="~/_ControlTemplates/PhilaGov/MetaTagsKeyWords.ascx" /> 
</Elements>

Here's the Head section of Master Page

<HEAD runat="server">
<META Name="GENERATOR" Content="Microsoft SharePoint">
<META Name="progid" Content="SharePoint.WebPartPage.Document">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
<META HTTP-EQUIV="Expires" content="0">
<SharePoint:RobotsMetaTag runat="server"/>
<Title ID=onetidTitle><asp:ContentPlaceHolder id=PlaceHolderPageTitle runat="server"/></Title>
<SharePoint:CssLink runat="server"/>
<SharePoint:Theme runat="server"/>
<SharePoint:ScriptLink language="javascript" name="core.js" Defer="true" runat="server"/>
<SharePoint:CustomJSUrl runat="server"/>
<SharePoint:SoapDiscoveryLink runat="server"/>
<asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server"/>
<SharePoint:DelegateControl runat="server" ControlId="AdditionalPageHead" AllowMultipleControls="true"/>
</HEAD>

UPDATE: Example page layout:

<%@ Page language="C#"   Inherits="Microsoft.SharePoint.Publishing.PublishingLayoutPage,Microsoft.SharePoint.Publishing,Version=12.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="SharePointWebControls" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="PublishingWebControls" Namespace="Microsoft.SharePoint.Publishing.WebControls" Assembly="Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="PublishingNavigation" Namespace="Microsoft.SharePoint.Publishing.Navigation" Assembly="Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<asp:Content ContentPlaceholderID="PlaceHolderAdditionalPageHead" runat="server">
    <PublishingWebControls:editmodepanel runat="server" id="editmodestyles">
            <!-- Styles for edit mode only-->
            <SharePointWebControls:CssRegistration name="<% $SPUrl:~sitecollection/Style Library/~language/Core Styles/zz2_editMode.css %>" runat="server"/>
    </PublishingWebControls:editmodepanel>
    <SharePointWebControls:CssRegistration name="<% $SPUrl:~sitecollection/Style Library/~language/Core Styles/rca.css %>" runat="server"/>
    <PublishingWebControls:editmodepanel runat="server" id="displaymodejs" PageDisplayMode="Display">
            <!-- JavaScript for to remove OverViewbox if its empty-->
            <script type="text/javascript" language="javascript">
                    $(document).ready(function () { 
                          $(".overviewBox>div").filter(function (index) { return $(this).children().length < 1; }).parent().remove();
                    });
            </script>
    </PublishingWebControls:editmodepanel>
</asp:Content>
<asp:Content ContentPlaceholderID="PlaceHolderPageTitle" runat="server">
                <SharePointWebControls:FieldValue id="PageTitle" FieldName="Title" runat="server"/>
</asp:Content>
<asp:Content ContentPlaceholderID="PlaceHolderMain" runat="server">
                <div class="widget breadcrumb">
                  <asp:SiteMapPath runat="server" id="SiteMapPath1" SkipLinkText="" SiteMapProvider="CurrentNavSiteMapProviderNoEncode"></asp:SiteMapPath>  
             </div>
             <div class="widget pageTitle">
                    <h1>
                    <SharePointWebControls:FieldValue id="HomePageTitleInTitleArea" FieldName="Title" runat="server"/></h1>
             </div>
             <div class="grid_15 colRight">
                 <div class="widget overviewBox">
                      <PublishingWebControls:RichHtmlField FieldName="OverViewContent1" runat="server" 
                                                           InputFieldLabel="Content">  
                      </PublishingWebControls:RichHtmlField>
                 </div>
                 <div class="widget WebPartEdit">
                      <PublishingWebControls:RichHtmlField FieldName="PublishingPageContent1" runat="server" 
                                                           InputFieldLabel="Content">  
                      </PublishingWebControls:RichHtmlField>
                 </div>
                 <div class="widget overviewBox">
                      <PublishingWebControls:RichHtmlField FieldName="OverViewContent2" runat="server" 
                                                           InputFieldLabel="Content">  
                      </PublishingWebControls:RichHtmlField>

                 </div>
                 <div class="widget WebPartEdit">
                      <PublishingWebControls:RichHtmlField FieldName="PublishingPageContent2" runat="server" 
                                                           InputFieldLabel="Content">  
                      </PublishingWebControls:RichHtmlField>

                 </div>
                 <WebPartPages:WebPartZone runat="server" Title="BottomZone" ID="BottomZone"><ZoneTemplate></ZoneTemplate></WebPartPages:WebPartZone>
                 <PublishingWebControls:editmodepanel runat="server" id="editmodepanel1">
                    <!-- Add field controls here to bind custom metadata viewable and editable in edit mode only.-->
                    <SharePointWebControls:NoteField FieldName="MetaKeywords" runat="server"></SharePointWebControls:NoteField>
                    <SharePointWebControls:NoteField FieldName="MetaDescription" runat="server"></SharePointWebControls:NoteField>
                  </PublishingWebControls:editmodepanel>

             </div>
             <div class="grid_5 colLeft">
                  <WebPartPages:WebPartZone runat="server" Title="LeftZone" ID="LeftZone"><ZoneTemplate></ZoneTemplate></WebPartPages:WebPartZone>
             </div>

</asp:Content>
Était-ce utile?

La solution

Here's a complete example of a working ASCX SharePoint DelegateControl. It adds the required Google Analytics stuff plus any meta keywords you define.

First, the feature.xml:

<Feature Id="INSERTYOURGUIDHERE"
  Title="Adds Google Analytics Counter (requires a Google Analytics ID)"
  Description="Activates feature for Google Analytics Web counter"
  Version="1.0.0.0"
  Scope="Web"
  Hidden="FALSE"
  ActivateOnDefault="FALSE"
  xmlns="http://schemas.microsoft.com/sharepoint/">
    <ElementManifests>
      <ElementManifest Location="elementManifest.xml"/>
    </ElementManifests>
</Feature>

Second, the elementManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <Control Id="AdditionalPageHead" ControlSrc="~/_controltemplates/GoogleAnalytics.ascx"></Control>
</Elements>

Third, the GoogleAnalytics.ascx:

<%@ Control Language="C#" compilationMode="Always" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Diagnostics" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Import Namespace="Microsoft.SharePoint.WebControls" %>
<%
    string keywords = "keyword-1,keyword-2";
    string idString = "UA-1234567-8";
    string requestProtocol = "http://www.";

    try
    {
        if (keywords != "")
        {
            // Add keywords meta tag
            Response.Write("\n\n<meta name=\"keywords\" content=\"" + keywords + "\" />\n");

            // Write debug output, use Microsoft "DebugView" locally on the server to watch the output 
            Trace.WriteLine("meta keywords: " + keywords);
        }

        if (idString != "")
        {
            // Check if HTTPS (SSL) is used to request this page
            if (Request.IsSecureConnection)
            {
                // Set appropriate SSL url
                requestProtocol = "https://ssl.";
            }

            // Add async script load to page head
            Response.Write("<script type=\"text/javascript\">var _gaq = _gaq || [];_gaq.push(['_setAccount', '" + idString + "']);_gaq.push(['_trackPageview']);_gaq.push(['_trackPageLoadTime']);(function() {var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;ga.src = '" + requestProtocol + "google-analytics.com/ga.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);})();</script>");
        }
    }
    catch (Exception ex)
    {
        Trace.WriteLine("Exception: " + ex.ToString());
    }
%>

You need to replace the keywords and idString variables with values of your choice and also create a valid feature id to pop into Feature Id="INSERTYOURGUIDHERE".

Also note the line starting with Trace.WriteLine. It shows how a simple tracing can be implemented and watched using the Microsoft DebugView (http://technet.microsoft.com/en-us/sysinternals/bb896647) utility.

You can use just a simple text editor (I prefer the free and open source Notepad++) and the Codeplex WSPBuilder to wrap it into a WSP and you're ready to deploy.

Once done, activate the feature on each SharePoint Website (SPWeb) of your choice and you're all set.

Autres conseils

You can develop a Delegate Control for the Head Section, by creating a SharePoint feature. That SharePoint feature can be enabled and disabled according to the Sites.

File -> New Project -> SharePoint Empty Project.

Add New Class and change its base class to System.Web.UI.WebControls.WebControl

Override required methods like OnLoad,CreateChildControls or Render.

Add New Module with Elements.xml and add the below tag. Ensure that the Safe property is set to true

<Control Id="AdditionalPageHead"  Sequence="100" ControlClass="addedclassFullName" ControlAssembly="$SharePoint.Project.AssemblyFullName$"  ></Control>

Instead of adding a class we can use an UserControl and refer it in ControlSrc property of Control tag in place of ControlClass and ControlAssembly.

Finally, deploy the feature.

Here is good tutorial

Here some best practices for using delegate controls in 2007

Thanks Guys for Your Help and suggestion now its working.I reset master Page and all check to reset all sites and subsites to reset to masterpage settings and its working.

Thanks Ronak

Licencié sous: CC-BY-SA avec attribution
Non affilié à sharepoint.stackexchange
scroll top