Wednesday 14 May 2008

Validating Custom Web Part Properties - the proper way!

Adding validation to custom web part properties (the proper way!) Thanks Ken Josling for this info!

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.IO;
using System.Resources;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace YourNamespace
{

public class YourWebPart : System.Web.UI.WebControls.WebParts.WebPart
{
private bool invalidConfiguration;
private string exceptionMessage;
private ResourceManager resourceManager;

public YourWebPart()
{
invalidConfiguration = false;
exceptionMessage = string.Empty;
resourceManager =
new ResourceManager("YourNamespace.Resource", GetType().Assembly);
}

private void invalidateConfiguration(string message)
{
invalidConfiguration = true;
exceptionMessage = message;
}

protected void AddInitializeControl()
{
bool hasRights = ((ISecurableObject)SPContext.Current.Web).DoesUserHavePermissions((SPBasePermissions)Microsoft.SharePoint.SPPermissionGroup.WebDesigner);

if (!hasRights)
return;

string editLink = Microsoft.SharePoint.WebPartPages.ToolPane.GetShowExtensibleToolPaneEvent(string.Format(@"'{0}'", this.UniqueID));
this.Controls.Add(new LiteralControl(
string.Format(exceptionMessage + resourceManager.GetString("WebPartHelpMessage"), editLink.Replace(@"ExtensibleView", @"Edit"))
));

}

protected override void CreateChildControls()
{
//Add your validation logic here
if(x)
{
invalidateConfiguration(resourceManager.GetString("SomeErrorMessage"));
}
if (y)
{
invalidateConfiguration(resourceManager.GetString("SomeOtherErrorMessage"));
}

if (invalidConfiguration)
{
AddInitializeControl();
}
else
{
//Render Web Part Here
}
}

protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
}
}
}

Monday 12 May 2008

Trying to use an SPWeb object that has been closed or disposed and is no longer valid

Trying to use an SPWeb object that has been closed or disposed and is no longer valid

When you get the error message above it is most likely that you have got a reference to the SPWeb object by using the SPContext as shown below

SPWeb web = SPContext.Current.Web;

There is no problem with using this method but you need to make sure that you do not close or dispose this SPweb object becase the SPContext.Current.Web is used by the Page and all the controls on the page.

So you should not use this web object in Using statements also.