Friday, August 14, 2009

How to avoid inline codes in user controls in SharePoint web parts

When I was at the beginning of developing web parts for SharePoint , I wanted to find a way of reducing the time consume to develop web parts using Web User Controls (*.ascx) as web parts.Otherwise you will have to write all the mark ups in the CreateChildControls method.

Check here how to use web application projects to develop web parts.

So I was very fond of that method till I figured out, this is not going to inline with the SharePoint deployment techniques.Especially if you are using wsp solution packages and 12 hive structure in Visual Studio with WSPBuilder.

Recently in a project that I was working with, I used a slightly different approach to which I was used to.That is not using web application projects but I used the user control(*.ascx file) with inline codes for the web part in the templatecontrol folder.

There are pros and cons having inline codes.

The code is visible to a person who has access to the server directly.

If it is a complex web part your lines of code will be very high and which will lead to readability and maintainability issues.

Today I managed to figure out how to move inline code into your main assembly of your SharePoint solution and I thought of sharing that with you.

SampleWebPartControl.ascx (user control)

What is important here is that the entry in the RED box in above image.That is the way you specify where the code behind can be found for this user control.

SampleWebPartCOntrol.cs(code behind)

The initialization of user controls you are using is paramount(check the RED box in this image).I had all sorts of problems till I sorted that out.

Solution Structure

Check where the items in the RED box in this image.

No comments: