Before jumping to actual development, lets know which scenarios demand the usage of Delegate Controls in sharepoint.
I have designed header image for my blog, and i want to have it on top of my sharepoint site.
So how to add it to all the pages in my sharepoint site. Simple ! Add it to master page, and automatically it will be on top of every page in that site.
Now, I have a scenario where
I want to hide the header image in all the environments except Production and i dont want to change the code/wsp based on environments.
This can even be applicable to the many other scenarios like Google Analytics Script, or some times, user want the season based or situation based header images or messages which can be changes just by activating ot deactivating features.
This is where Delegate Controls in sharepoint come to the picture. Any .NET developer can answer the Question
"What is a Delegate?"
The answer is "Its a Pointer to Function / Method", in this case, Delegate Control is a pointer to a Control which can be replaced at runtime based on Feature Activation or Deactivation.
Now that we understood the purpose of Delegate control, we will look at devlopment steps involved.
Step 1: Open the Custom Master Page and add the below peice of code.
<SharePoint:DelegateControl runat="server" ControlId="BlogLogoControl"/>
The ControlId is of most significant part, which tells sharepoint to substitute delegate control with any control with same ID.
Step 2: Add the User control to project. I named it as ucLogoControl.ascx. I have the image BlogHeader.jpg deployed to Style Library/Images in my site. SO add the below peice of code to User control.
<img src="http://www.codeproject.com/Style Library/Images/BlogHeader.jpg"/>
Step 3: Add a Module to project which will take care of adding the user control to Delegate control. I named it as "DelegateModule". Delete sample.txt file and modify the Elemnts.xml to resemble something like this.
<Elements xmlns="<a href="http://schemas.microsoft.com/sharepoint/">http://schemas.microsoft.com/sharepoint/</a>">
<Control Id = "BlogLogoControl" Sequence="90" ControlSrc="~/_controltemplates/SPDelegateProject/ucLogoControl.ascx"/>
Step 4: Create a feature and add "DelegateModule" to it. I named it "Site.LogoFeature".
Let me summarize all the actions once before deployment.
- We have removed the image from Masterpage
- Created a new usercontrol and added the image inside the user control.
- Created a module in which elements.xml signifies the control to be loaded in runtime instead of delegate control .
- Create a feature and associate the module to the newly created feature.
Now when you activate the feature, the delegate control will be substituted with my Image User control. If i dont want to display it, i will just disable the "Site.LogoFeature" and that will tell sharepoint will not substitue anything in place of delegate control.
Search for "SPDelegateProject.zip" in here.