SharePoint Web Part Basics

All web parts are based on the same basic ingredients. When I started developing on my first web parts I did some extra work to find out the best practices. This post is meant to work as a simple reference and to answer some of the questions I had when I first started.

What web parts events should I use?

There are many different opinions on this. This is mine:

  • Never put code in the constructor as it might be called even if the object is later never used
  • In the OnInit initialize any controllers etc. you might have
  • In the CreateChildControls method create your controls, but don’t populate them. Note that it is a common practice to define all the controls and the wepart layout in a separate control class to keep the web part clean.
  • In the OnPreRender load the data into the controls and setup any async task you might need (they will be executed next)

How to register JavaScript?

There are many ways to include JavaScript on a page, the right one depends on your need. To include a script to to be executed directly after page load use the RegisterStartupScript combined with the ExecuteOrDelayUntilScriptLoaded (SOD) or _spBodyOnLoadFunctionNames.push functions:

public static class SharePointScriptHelper
{
public static string ExecuteOrDelayUntilScriptLoaded(Control control, string script, string after)
{
string script = string.Format("ExecuteOrDelayUntilScriptLoaded(function(){{{0}}}, '{1}');", script, after);
ScriptManager.RegisterStartupScript(control.Page, typeof(Page), "Script_" + control.ID, script, true);
}
}
SharePointScriptHelper.ExecuteOrDelayUntilScriptLoaded(this, "alert('Hello world!');", "SP.js");

The first mentioned takes care of the correct load order of scripts.

To include e.g. a library that is not meant to be directly executed use e.g. the RegisterClientScriptInclude method:

ScriptManager.RegisterClientScriptInclude(this.Page, typeof(Page), "MyScriptNamespace", ScriptFileUrl);

The point in using the ScriptManager is to avoid having the same script included multiple times, hence the key parameter in e.g. RegisterclientScriptInclude. The class offers a lot of functions that are worth taking a closer look at.

Note that is is a good practice to wrap you scripts in a “class”/namespace to avoid e.g. function name collisions with other scripts.

To easily include the web part id in your inline scripts you can use the ReplaceTokens function of the web part class to do this. It will simply replace tokens like e.g. _WPID_ with the correct property values.

How to include CSS on a page?

CssRegistration css = new CssRegistration();
css.After = "corev4.css";
css.Name = Settings.StyleSheetFileUrl;
this.Controls.Add(css);

I have not yet had a chance to test SharePoint 2013 to see if it works to refer to the corev4.css also in that version.

Where to define configuration parameters?

The web part definition file (yourwebpart.webpart) is definitely the only correct place. This way they the properties are fully customizable by the site owners when necessary.

Never store passwords in any file as they belong in the secure store service. You can prevent property values from being exportable for a simple way of hiding them.

How should I define my layout?

The most flexible and powerful way is to use XSLT for the rendering. You can implement it your self or inherit the DataFormWebPart class.

Where should I put the CSS, image and other files?

Put them in the appropriate SharePoint mapped folders. Always create a sub folder for you web part and give it a unique name e.g. based on the namespace of the main class.

How to do logging and debug?

Use the inbuilt framework. The most elegant solution would be to write your own service class deriving from the SPDiagnosticsServiceBase but note that it will need to be registered at deployment time.

public static class SPDiagnosticsServiceExtension
{
public static void WriteTrace(this SPDiagnosticsService service, string message, string categoryName, TraceSeverity severity)
{
SPDiagnosticsCategory category = new SPDiagnosticsCategory(categoryName, TraceSeverity.Unexpected, EventSeverity.Information);
service.WriteTrace(0, category, severity, message);
}
}

Usage

SPDiagnosticsService.Local.WriteTrace(ex.ToString(), "Web Parts", TraceSeverity.Unexpected);

I strongly recommend enabling the Developer dashboard and using the SPMonitoredScope to help optimize the performance of your web part.

That’s all for now, more to to come later.

Advertisements