How to change web part property values - sharepoint

In a SharePoint 2007 web part, I want to delete an existing property and replace it with a property using a different name. I want to get the value from the existing property and assign it to the new property.
How should I do this?

In summary:
Get a reference to the page containing the web part.
Get a reference to the web part itself.
Change the property value.
Save the change.
In code:
using (SPSite site = new SPSite("http://sharepoint"))
using (SPWeb web = site.OpenWeb("Web Title"))
using (SPLimitedWebPartManager webPartManager =
web.GetLimitedWebPartManager("default.aspx", PersonalizationScope.Shared))
{
try
{
foreach (WebPart webPart in webPartManager.WebParts)
{
if ((webPart.Title == "Web Part Title") && (!webPart.IsClosed))
{
YourWebPart wp = (YourWebPart)webPart;
wp.NewProperty = wp.OldProperty;
webPartManager.SaveChanges(wp);
web.Update();
break;
}
}
}
finally
{
webPartManager.Web.Dispose();
}
}
Replace the following in this code example:
"http://sharepoint" - the address of your SharePoint site
"Web Title" - the title of the SharePoint web containing the web part to be changed (or use one of the other OpenWeb overloads
"default.aspx" - filename of the page containing the web parts
"Web Part Title" - title given to the web part on the page
YourWebPart - class name of the web part to change
NewProperty/OldProperty - names of the properties to change

Related

Set different value for Sharepoint custom property of same web part in multiple different pages

I have visual web part and i am attempting to set custom property unique value on each pages. For example i have two aspx pages. Deal.aspx and Fund.aspx. Both page is having same web part used. When i set the value custom property in web part of Deal.aspx the same value gets reflect in Fund.aspx page web part as well. I read about PersonalizationScope but it did not help for my scenario. Below is the custom property i have created.
public static string ListName;
[Category("Extended Settings"),
Personalizable(PersonalizationScope.User),
WebBrowsable(true),
WebDisplayName("Enter List Name"),
WebDescription("Please Enter a List Name")]
public string _ListName
{
get { return ListName; }
set
{
// Sample Validation
Regex oRegEx = new Regex("[a-zA-Z]+");
if (!oRegEx.IsMatch(value))
throw new Microsoft.SharePoint.WebPartPages.
WebPartPageUserException(
"Please enter alphabeth characters only");
ListName = value;
}
}
Problem is not in SharePoint or PersonalizationScope. It works fine. Problem is in static property ListName. Static properties are "shared" between all instances of the same class. So all your webparts will have the same value there.

How to get a reference to custom settings in webpart from a page within webpart?

I created a webpart, then I created a second .cs page that will render custom html. It basically just a simple page to show an image. However in the second .cs page, I need to access custom settings in the Web Part. How can I access custom tool pane settings in the main web part when the link to the secondary page is clicked?
The second page is generated from VS 2010 and is in the layouts folder, looks like:
public partial class GetFile : LayoutsPageBase
{
I am thinking I have to inherit something from the web part in order to do this, but really not sure how?
You can access the Web part properties using the SPLimitedWebPartManager class by reading the web part collection and their properties on the page as shown below,
var web = SPContext.Current.Web;
var currentPageURL = "//URL of the page on which the Web part is present";
var page = web.GetFile(currentPageURL);
using (SPLimitedWebPartManager webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
try
{
var webPartList = from System.Web.UI.WebControls.WebParts.WebPart webPart in webPartManager.WebParts select webPart;
foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in webPartList.ToList())
{
if (webPart.Title.ToLower() == "//Name of the web part for which you want to read the properties")
{
PropertyInfo[] wptProperties = webPart.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in wptProperties)
{
if (property.Name == "//Name of the web property which you want to get")
{
// Following code updates the web part property, you can also read it
property.SetValue(webPart, "value to be set", null);
webPartManager.SaveChanges(webPart);
break;
}
}
}
}
Response.Redirect(currentPageURL);
}
finally
{
webPartManager.Web.Dispose();
}
}

Cannot save all of the property settings for this Web Part - Sharepoint

"Cannot save all of the property settings for this Web Part. The
default namespace "http://schemas.microsoft.com/WebPart/v2" is a
reserved namespace for base Web Part properties. Custom Web Part
properties require a unique namespace (specified through an
XmlElementAttribute on the property, or an XmlRootAttribute on the
class)."
No where do I get help regarding this error.
This is when adding custom properties to my webpart, why cant I save the properties when I edit my webpart and click on save/apply? (then I get that error)
Code--
[DefaultProperty("Text"), ToolboxData("<{0}:CustomPropertyWebPart runat=server></{0}:CustomPropertyWebPart>"),
XmlRoot(Namespace = "ExecuteStoreProc")]
public class CustomPropertyWebPart : Microsoft.SharePoint.WebPartPages.WebPart
{
const string c_MyStringDefault = "Sample String";
}
// Create a custom category in the property sheet.
[Category("Custom Properties")]
// Assign the default value.
[DefaultValue(c_MyStringDefault)]
// Property is available in both Personalization
// and Customization mode.
[WebPartStorage(Storage.Personal)]
// The caption that appears in the property sheet.
[FriendlyNameAttribute("Custom String")]
// The tool tip that appears when pausing the mouse pointer over
// the friendly name in the property pane.
[Description("Type a string value.")]
// Display the property in the property pane.
[Browsable(true)]
[XmlElement(ElementName = "MyString")]
// The accessor for this property.
public string MyString
{
get
{
return _myString;
}
set
{
_myString = value;
}
}
Can you try going to Site Settings > Galleries > Web Part > New
In that window, put a checkbox next to the webpart you are trying to add, then click Populate
If its populate correctly then it is working otherwise there is some error in the webpart.
Return to your webpage where you want to add the webpart, try to add the webpart by selecting it in the gallery.
If this works (you were able to add it to your page), you can open the webpart added in your webpart gallery (Site Settings > Galleries > Web Part) and compare it to your own .dwp file to see what you did wrong.
Hope this helps

How to programmatically add target lists to the what's new web part in Sharepoint (or how to handle undocumented namespaces)

From code I've automatically created a lot of similar sites (SPWeb) in my site collection from a site template (in Sharepoint Foundation). Every site has a home page on which I've added the "what's new" web part (found under "Social collaboration").
Even though the web part has several "target lists" (I'd have called it "source lists") added to it on the template site, this connection is lost on the sites created from the template. So I need to programmatically find all these web parts and add the target lists to them. Looping the web parts is not an issue - I've done that before - but I can't seem to find a word on the net on how to go about modifying this particular web part. All I have is a brief intellisense.
I've found out that it recides in the
Microsoft.SharePoint.Applications.GroupBoard.WebPartPages
namespace, but on the lists provided on MSDN this is one of very few namespaces that doesn't have a link to a reference documentation.
Does anyone have any experience of modifying this web part from code? If not, how would you go about to find out? I can't seem to figure out a method for this..
Here is how I did it. It worked really well. I had a feature that created several list instances and provisioned the What's New web part. In the Feature Receiver, I looped through all of the list instances, indexed the Modified field, and then added the list to the web part:
private void ConfigureLists(SPWeb web, SPFeatureReceiverProperties properties)
{
List<Guid> ids = new List<Guid>();
SPElementDefinitionCollection elements =
properties.Feature.Definition.GetElementDefinitions(new CultureInfo((int)web.Language, false));
foreach (SPElementDefinition element in elements)
{
if ("ListInstance" == element.ElementType)
{
XmlNode node = element.XmlDefinition;
SPList list = web.Lists[node.Attributes["Title"].Value];
SPField field = list.Fields[SPBuiltInFieldId.Modified];
if (!field.Indexed)
{
field.Indexed = true;
field.Update();
}
ids.Add(list.ID);
}
}
string targetConfig = string.Empty;
foreach (Guid id in ids)
{
targetConfig += string.Format("'{0}',''\n", id);
}
SPFile file = web.GetFile("Pages/default.aspx");
file.CheckOut();
using (SPLimitedWebPartManager manager = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
WhatsNewWebPart webpart = null;
foreach (System.Web.UI.WebControls.WebParts.WebPart eachWebPart in manager.WebParts)
{
webpart = eachWebPart as WhatsNewWebPart;
if (null != webpart)
{
break;
}
}
if (null != webpart)
{
webpart.TargetConfig = targetConfig;
manager.SaveChanges(webpart);
}
}
file.CheckIn("ConfigureWebParts");
file.Publish("ConfigureWebParts");
file.Approve("ConfigureWebParts");
}
If you are unsure about the property, export the web part from the browser, then open the .webpart/.dwp file with a text editor. Somewhere in the xml will be a reference to the source list.
*.webparts are usually easier to modify, just set the property.
*.dwps are harder because you sometimes have to get the property (eg ViewXML), then load it into an XmlDocument, then replace the property, and write the xml document string value back to ViewXML.

Web Part connections in site definitions

I have requirement of specifying web part connections in onet.xml. So when site is created using this site definition the said web parts are already connected and ready to use. Which properties I need to specify for that particular web parts in onet.xml.
I have also hit the wall on this one sometime last year! It looks like connections can no longer be specified on Web Parts in the new .webpart format as they could in the old .dwp format. I ended up including a custom feature in the site definition like kpinhack also suggests. My code for connecting the Web Parts is listed below. The method is just designed for connecting two Web Parts of different types - it does not support multiple Web Parts of the same type on the same page. But I am sure you'll catch the general idea.
private void ConnectWebParts(SPWeb web, string pageName, Type providerType, Type consumerType)
{
SPFile file = web.GetFile(pageName);
SPList list = null;
if (file.InDocumentLibrary)
{
list = file.Item.ParentList;
if (list.ForceCheckout) file.CheckOut();
}
SPLimitedWebPartManager webPartManager =
web.GetLimitedWebPartManager(
pageName,
System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
WebPart provider = null;
foreach (WebPart wp in webPartManager.WebParts)
{
if (wp.GetType() == providerType)
{
provider = wp;
break;
}
}
foreach (WebPart consumer in webPartManager.WebParts)
{
if (consumer.GetType() != consumerType) continue;
ProviderConnectionPointCollection providerConnections = webPartManager.GetProviderConnectionPoints(provider);
ProviderConnectionPoint providerConnection = providerConnections[0];
ConsumerConnectionPointCollection consumerConnections = webPartManager.GetConsumerConnectionPoints(consumer);
ConsumerConnectionPoint consumerConnection = consumerConnections[0];
SPWebPartConnection con = webPartManager.SPConnectWebParts(provider, providerConnection, consumer, consumerConnection);
webPartManager.SPWebPartConnections.Add(con);
}
if (list != null)
{
if (list.ForceCheckout)
{
file.CheckIn("Added Web Part Connections");
}
if (list.EnableVersioning && list.EnableMinorVersions)
{
file.Publish("Added Web Part Connections");
}
}
}
I would configure the WebParts in the SiteProvisioning-Feature, by implementing the 'OnActivated'-Eventhandler. That way the code will run when the website is created, and you can handle errors the way you like it (i.e. if the WebParts are not available when the website is created - for whatever reason)
I hope this helps!
you would need to use the < AllUsersWebPart > tag to declare your web parts, and then declare your connections within the enclosed < WebPart > elements.
example

Resources