I have the following code in a method that generates tabbed web parts on any page in SharePoint 2010.
The problem is that it will not work for users who have Read access only on a SharePoint site. It will work when those users have Contribute access.
So even though I have elevated permissions in the code it does not actually elevate the permissions at the point where it is needed.
if (panel != null)
{
try
{
using (SPLimitedWebPartManager wpManager = SPContext.Current.Web.GetLimitedWebPartManager(HttpContext.Current.Request.Url.ToString(), PersonalizationScope.Shared))
{
try
{
// Elevated previleges required for EXPORT and IMPORT. Else Users with normal read access will get errors.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Retrieve the web part titles in the ConfigureTabs XML string for this tab.
var webPartTitles = from t in xDocument.Descendants("webPart")
where (string)t.Parent.Attribute("name") == (string)e.Item.DataItem
select (string)t.Attribute("title");
foreach (string wpTitle in webPartTitles)
{
foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in wpManager.WebParts)
{
// Find the matched closed web part in WebParts collection
if (webPart.Title == wpTitle && webPart.IsClosed == true)
{
string errorMessage;
//ADD EXPORT PROPERTY
webPart.ExportMode = WebPartExportMode.All;
MemoryStream stream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(stream, System.Text.Encoding.UTF8);
// Export the closed webpart to a memory stream.
wpManager.ExportWebPart(webPart, writer);
writer.Flush();
stream.Position = 0;
XmlTextReader reader = new XmlTextReader(stream);
// Import the exported webpart.
System.Web.UI.WebControls.WebParts.WebPart newWebPart = wpManager.ImportWebPart(reader, out errorMessage);
reader.Close();
writer.Close();
// Show the imported webpart.
panel.Controls.Add(newWebPart);
break;
}
}
}
});
}
catch (Exception ex)
{
// For debugging use only.
Label label = new Label();
label.Text = "Please check your XML configuration for error. " + Environment.NewLine + ex.Message;
panel.Controls.Add(label);
}
}
}
catch (Exception ex)
{
// For debugging use only.
Label label = new Label();
label.Text = "Please Check SPContext.Current.Web is not null. " + Environment.NewLine + ex.Message;
panel.Controls.Add(label);
}
}This snippet of code was originally pulled from a microsoft technet article on creating Tabbed web parts "the correct way" but it doesn't work in all scenarios.
Is there a way to get this code working for Read/Visitors to a SharePoint site?