Wednesday, August 11, 2010

Export Webpart programmatically using SPLimitedWebpartManager

Export Webpart programmatically

==========================================================================

private void ExportWebpart(SPLimitedWebPartManager wpm, string strFilePath)
{

XmlTextWriter writer;
foreach (var webPartOnPage in wpm.WebParts)
{
try
{
System.Web.UI.WebControls.WebParts.WebPart webPartObj = (System.Web.UI.WebControls.WebParts.WebPart)(webPartOnPage);

if (!Directory.Exists(strFolderPath))
{
Directory.CreateDirectory(strFolderPath);
}
//Store below detail into xml since some web part does not export (eg: filter text web part)
// So while import we can use below detail and addwebpart using assembly name.

// RemoveSpecialCharacters(webPartObj.Title);
// wpm.GetZoneID(webPartObj);
// webPartObj.ZoneIndex;
// webPartObj.GetType().AssemblyQualifiedName;

writer = new XmlTextWriter(strFilePath, Encoding.UTF8);
wpm.ExportWebPart(webPartObj, writer);

writer.Flush();
writer.Close();
}
catch {}

}

}

==========================================================================

This above function can be use for following points:-

SPLimitedWebpartManager.ExportWebPart(Webpart, XmlWriter) throws XmlException
like below:-
The prefix '' cannot be redefined from '' to 'http://schemas.microsoft.com/WebPart/v3' within the same start element tag.
Then change xmlwriter to xmltextwriter. Same you can see in above function.

or

SPLimitedWebpartManager.ExportWebPart

The biggest issue:-
============================

SPLimitedWebpartManager.ExportWebPart(Webpart, XmlWriter) throws XmlException
XmlException when you use Text Filter Web Part (SPSlicerTextWebPart)
As per understanding, There is no solution for this. So I have other work around for this.

Why we are exporting? Since we might want import to some other site.

So what we can do, while export, store webpart detail in xml file. And while import creates 2 function as mentioned below:-

1. this is for those which have .webpart file

for this use my function "AddWebPartToPage" which u can refer from other article.

2. This is: for those which does not have webpart file means it couldn’t export. Then use following function to addwebpart

private void AddWebPartToPageUsingAssembly(string strWebPartName, SPWeb oWeb, string strZoneId, int ZoneIndex, SiteWebPart webpartSetting)
{
//here webPartSetting object contains the properties of those webpart which couldn’t export
// you can get these object using the xml which you have exported while webpart export.

SPFile file = null;
SPLimitedWebPartManager manager = null;

try
{
if (webpartSetting != null)
{
string strType = webpartSetting.Settings.AssemblyType;
Type type = Type.GetType(strType);
Assembly assemblyType = type.Assembly;
System.Web.UI.WebControls.WebParts.WebPart webPartObj = (System.Web.UI.WebControls.WebParts.WebPart)assemblyType.CreateInstance(type.FullName);
webPartObj.ChromeType = PartChromeType.None;
webPartObj.Title = webpartSetting.Settings.Title;

if (String.Compare(webPartObj.GetType().Name, "SPSlicerTextWebPart", true) == 0)
{
(((Microsoft.SharePoint.Portal.WebControls.SPSlicerBaseWebPart)(webPartObj))).FilterName = webpartSetting.Settings.FilterName;
}
file = oWeb.GetFile(strPageUrl);

if (file.CheckOutStatus == SPFile.SPCheckOutStatus.None)
{
file.CheckOut();
manager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
manager.AddWebPart(webPartObj, strZoneId, ZoneIndex);
oWeb.Update();
}
}

}
catch (Exception ex)
{
// Exception details
}
finally
{
if (manager != null)
manager.Dispose();

if (file != null)
{
file.CheckIn("added web parts");
file.Publish("added web parts");
}
}
}
===============================================================

Thanks!
Avinash Dad

Retrieve webpart connection details programmatically using SPWebPartConnection

If you wish to retrieve the webpart information programmatically then you can use following function.


private void FindConnectedWebPart(SPLimitedWebPartManager wpm)
{
SPWebPartConnectionCollection webPartConColl = wpm.SPWebPartConnections;
try
{
foreach (SPWebPartConnection webPartCon in webPartConColl)
{
string strProviderTitle = RemoveSpecialCharacters(webPartCon.Provider.Title);
string strConsumerTitle = RemoveSpecialCharacters(webPartCon.Consumer.Title);
if (String.Compare(webPartCon.Provider.GetType().Name, "SPSlicerTextWebPart", true) == 0)
{
string strFilterName = ((Microsoft.SharePoint.Portal.WebControls.SPSlicerBaseWebPart)(webPartCon.Provider)).FilterName;
}
TransformableFilterValuesToFilterValuesTransformer transformerMapping = (TransformableFilterValuesToFilterValuesTransformer)webPartCon.Transformer;
// use these details as per your requirements
}
}
catch (Exception ex)
{
// exception detail
}

}


Thanks!
Avinash Dad

Add Web Part programmatically using SPLimitedWebPartManager

Add Web Part programmatically

=========================================================================


public void AddWebPartToPage(string webPartFullName, SPWeb web, string zoneId, int zoneIndex)
{
SPFile file = null;
XmlUrlResolver xmlResolver = new XmlUrlResolver();
xmlResolver.Credentials = CredentialCache.DefaultCredentials;
FileStream fs = new FileStream(webPartFullName, FileMode.OpenOrCreate);
XmlReader reader = new XmlTextReader(fs);
string errorMsg;
SPLimitedWebPartManager manager = null;

try
{
file = web.GetFile(strPageUrl);
if (file.CheckOutStatus == SPFile.SPCheckOutStatus.None)
{
file.CheckOut();
manager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
System.Web.UI.WebControls.WebParts.WebPart tempWebPart = manager.ImportWebPart(reader, out errorMsg);
manager.AddWebPart(tempWebPart, zoneId, zoneIndex);
web.Update();
}
}
catch (Exception ex)
{
// write exception
}
finally
{
if (manager != null)
manager.Dispose();

if (file != null)
{
file.CheckIn("added web parts");
file.Publish("added web parts");
}
if (fs != null)
{
fs.Close();
fs.Dispose();
}

}
}
=========================================================================

this above function can be use for following points:-

Import WebPart programmatically using SPLimitedWebPartManager
or
Add Web Part programmatically using SPLimitedWebPartManager
or
Add Web Part to Page Programmatically

or

any exception comes like this:-
Throws this error on ImportWebPart..."The file you imported is not
valid. Verify that the file is a Web Part description file (*.webpart
or *.dwp) and that it contains well-formed XML."

then its issue with credential. please us CredentialCache.DefaultCredentials as mention in above function.

or

any exception comes like this:-
"Object reference not set to an instance of an object" while ImportWebPart
then its isse with loading file. Dont use File to load use FileStream as mentioned in above function.

or

SPLimitedWebPartManager.AddWebPart():



Thanks!
Avinash Dad

Connect webparts programmatically using SPConnectWebParts

If you wish to connect two webpart where you have webpart consumer and webpart provider object then you can use following idea to implement functionality.

========================================================================
private void ConnectWebPartOnPage(SPWeb oWeb, WebPart webPartConsumer, WebPart webPartProvider, string MappingId)
{
SPFile file = null;
SPLimitedWebPartManager manager = null;
file = oWeb.GetFile(strPageUrl);

try
{
if (file.CheckOutStatus == SPFile.SPCheckOutStatus.None)
{
file.CheckOut();
manager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);

ConsumerConnectionPoint consumerConnection = null;
foreach (ConsumerConnectionPoint point in manager.GetConsumerConnectionPoints(webPartConsumer))
{
if (point.InterfaceType == typeof(IFilterValues))
{
consumerConnection = point; break;
}
}
ProviderConnectionPoint providerConnection = null;
foreach (ProviderConnectionPoint point in manager.GetProviderConnectionPoints(webPartProvider))
{
if (point.InterfaceType == typeof(Microsoft.SharePoint.WebPartPages.ITransformableFilterValues))
{
providerConnection = point; break;
}
}

TransformableFilterValuesToFilterValuesTransformer transformMapping = new TransformableFilterValuesToFilterValuesTransformer();
transformMapping.MappedConsumerParameterName = MappingId;
manager.SPConnectWebParts(webPartProvider, providerConnection, webPartConsumer, consumerConnection, transformMapping);

oWeb.Update();
}
}
catch (Exception ex)
{
// exception here
}
finally
{
if (manager != null)
manager.Dispose();

if (file != null)
{
file.CheckIn("Connected web parts, if any");
file.Publish("Connected web parts, if any");
}
}
}
===============================================================================

this above function can be use for following points:-


Programmatically connect a Consumer WebPart & a Provider WebPart

or

How to connect WebParts Programmatically?

or

Connecting webparts

or

use of ConsumerConnectionPoint and ProviderConnectionPoint

or

use of SPConnectWebParts

or

How to connect Web Parts programmatically in WSS 3


Thanks
Avinash Dad