Monday, April 13, 2009

Activate the feature and add web parts through code

I would provide step by step process to add a web part in the web part gallery for a spcific site and activate the feature to show it in the default.aspx page.

I assume you have created the web part separately and placed it in the GAC and added in the safecontrol.

I am not showing you the whole solution but tell you the important steps and functions so that you can use it in your program.


1. Prepare DWP file through your code and add the webpart file in the web part gallery

public static bool AddWebPartsToGallery(string SiteURL)
{
bool isSuccess = false; //assume failure

string dwpUserControlContainer = @"" +
"" +
"" +
" Demo Web Part.
" +
"DemWebPart,Version=1.0.0.0,Culture=neutral,PublicKeyToken=2d5a04d2e0ff8065" +
"DemoWebParts " +
"
";
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SiteURL))
{
using (SPWeb web = site.OpenWeb())
{
SPList webPartGallery = web.GetCatalog(SPListTemplateType.WebPartCatalog);
SPFolder folder = webPartGallery.RootFolder;
web.AllowUnsafeUpdates = true;
if (folder != null)
{
folder.Files.Add("DemoWebpart.dwp", dwpUserControlContainer, true);
folder.Update();
isSuccess = true;
}
web.AllowUnsafeUpdates = false;
}
}
});
}
catch (Exception ex)
{
isSuccess = false;
}
return isSuccess;
}

2. Activate your feature and add the web part in the default.aspx

private void ActivateFeature(string SiteU
{

try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SiteURL))
{
using (SPWeb web = site.OpenWeb())
{
System.Globalization.CultureInfo oCultureInfo = new System.Globalization.CultureInfo(1033);
SPFeatureDefinitionCollection collFeatureDefinitions = SPFarm.Local.FeatureDefinitions;
foreach (SPFeatureDefinition oFeatureDefinition in collFeatureDefinitions)
{
if (oFeatureDefinition.GetTitle(oCultureInfo) == “Your feature name”)
{
Guid guidFeatureDefinitionID = oFeatureDefinition.Id;

if (oFeatureDefinition.Scope == SPFeatureScope.Site)
{
SPFeatureCollection collFeatureCollection = site.Features;
SPFeature oFeature = collFeatureCollection.Add(guidFeatureDefinitionID);
break;
}

}
}
}
}
});
}
catch
{
}

}
private static bool AddToPage(string SiteURL, string dwp)
{
bool isSuccess = false; //assume failure

try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SiteURL))
{
using (SPWeb web = site.OpenWeb())
{
SPWebPartCollection coll = web.GetWebPartCollection("default.aspx", Storage.Shared);
coll.Add(dwp);
isSuccess = true;
}
}
});
}
catch (Exception ex)
{
LogException(ex);
isSuccess = false;
}
return isSuccess;
}

2 comments: