I want to read text form my webpart. Its a simple one: just a line of text - nothing else.
I can get properties of my webparts (like title, desc etc) but can't get the content of it. Any ideas how to retreive this information? Thanks in advance.
using (SPSite site = new SPSite("http://mysite/pwa/some_web"))
{
using (SPWeb web = site.OpenWeb())
{
SPFile file = web.GetFile("default.aspx");
using (SPLimitedWebPartManager wpm = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
{
foreach (Microsoft.SharePoint.Client.WebParts.WebPart wp in wpm.WebParts)
{
Console.WriteLine("Web part: {0}", wp.Title);
}
}
}
}
WebPart is the base class where other web part classes inherit from, and only contains the common properties such as Title. To read a specific property, you need to cast that wp object to the actual class of the web part.
Within the foreach loop:
MyWebPartClass mwp = (MyWebPartClass)wp;
Console.WriteLine(wp.SomeProperty);
Where MyWebPartClass inherits WebPart and declares the property SomeProperty. Note that you should also check first that the wp object is in fact a webpart of your class, in case there are more web parts on the same page
Related
I have try to change default view query using C# but it's not working. I can change JSLink property, but not XmlDefinition. Any idea to workaround or what I'm doing wrong?
var webPart = listWebPart.WebPart.
clientContext.Load(webPart.Properties);
clientContext.ExecuteQuery();
webPart.Properties["XmlDefinition"] = newQuery;
listWebPart.SaveWebPartChanges();
clientContext.Load(listWebPart);
clientContext.ExecuteQuery();
It's list webpart on some page.
You can get the LimitedWebPartManager for the page with the GetLimitedWebPartManager function on SharePoint Online as well, MSDN. You can then load the WebParts using the LimitedWebPartManager as below:
var page = ctx.Web.GetFileByServerRelativeUrl(pageUrl);
LimitedWebPartManager wpMgr = page.GetLimitedWebPartManager(Microsoft.SharePoint.Client.WebParts.PersonalizationScope.Shared);
ctx.Load(wpMgr.WebParts);
ctx.ExecuteQuery();
This will load all the webparts on the page. You can then get the WebPartDefinition of the webpart you require using it's index:
WebPartDefinition webPartDef = wpMgr.WebParts[webpartIndex];
ctx.Load(webPartDef);
ctx.ExecuteQuery();
You can now finally update the desired property and save the definition:
webPartDef.WebPart.Properties["XmlDefinition"] = newQuery;
webPartDef.SaveWebPartChanges();
webPartDef.CloseWebPart();
ctx.ExecuteQuery();
Hopefully this will help you update your webpart properties
Background
We have a custom developed installed .WSP on a SharePoint 2007 environment and have been in the process of upgrading to 2010. With the upgrade the custom event trigger no longer worked so trying to update and make it work in 2010. But I am running into one issue. Original developers no longer here and I've been the lucky one to have to figure this one out without much of a background with SP Dev.
Goal
When a new list item is created trigger event. Within event, create a shared folder using Item Name and return url, create a wiki-page using item name and include shared document link and return url to wiki page. Part three is update newly created list item with the New Folder url and Wiki Page URL.
Issue
I've gotten the first two parts working but so far have been unable to update the newly created list item with the new Links. I'm able to get the links. I've tried all the basic stuff for updating the list that I have been able to find online with no luck. Nothing to complicated(or so I think). But code is included below. VS is not installed on the server so unable to run debug mode, I don't have direct access to the server. When you create the item there are no client/user side error. Haven't been able to find a log file that has any, that is if it collects errors if the script were to fail out.
Initiation of the Event
public class CreateWikiAndFolder : Microsoft.SharePoint.SPItemEventReceiver
{
public override void ItemAdded(SPItemEventProperties properties)
{
try
{
//this.DisableEventFiring();
base.EventFiringEnabled = false;
string sUrlOfWikiPage = string.Empty;
string sUrlOfNewFolder = string.Empty;
string sSubsiteRUL = string.Empty;
string sCurrentItemTitle = properties.ListItem["Title"].ToString();
string sWikiListName = "TR Wikis";
string sDocLibName = "Shared Documents";
string sTRListID = "TR Status";
if (sTRListID.ToUpper().Equals(properties.ListTitle.ToString().ToUpper()))
{
//Create the Folder
sUrlOfNewFolder = CreateFolder(properties.ListItem.Web, sDocLibName, sCurrentItemTitle);
//Create the Wiki
string ItemDispFormUrl = String.Concat(properties.ListItem.Web.Url, "/", properties.ListItem.ParentList.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url, "?ID=", properties.ListItem.ID.ToString());
sUrlOfWikiPage = CreateWiki(properties.ListItem.Web, sWikiListName, sCurrentItemTitle, ItemDispFormUrl, sUrlOfNewFolder);
//Update the current TR Item
//Have tried. properties.ListItem["WikiURL"] = sUrlOfWikiPage + ", " + "Wiki";
SPListItem myListItem = properties.ListItem;
SPFieldUrlValue shareFolderURLValue = new SPFieldUrlValue();
shareFolderURLValue.Description = "Shared Folder";
shareFolderURLValue.Url = sUrlOfNewFolder ;
myListItem["SharedFolder"] = shareFolderURLValue;
//I've tried each one separate and together to no luck
myListItem.UpdateOverwriteVersion();
myListItem.Update();
//properties.ListItem.UpdateOverwriteVersion();
}
base.EventFiringEnabled = true;
}
}
}
Note that this is the last thing needed to be figured out for our upgrade.
Got it working. I did both of these at the same time so I'm not sure if it was the combination of both or only one of the items. But one I removed the myListItem.UpdateOverwriteVersion(); line and surrounded the item updated with web.AllowUnsafeUpdates being set to true before and then back to false afterwards.
Also as a note to others, you need to save the properties.ListItem to its own SPListItem which you then update versus trying to manipulate the values at the properties.ListItem["Attribute"], and then update the properties.ListItem.Update. SharePoint doesn't allow the latter option so you have to save to an independent SPListItem, and then modify and update that one. This might not be the best SharePoint lingo, but that is what needs to be done.
Hopefully you can help. I am working on a Browser Enabled InfoPath 2010 form that lives in a Document Library on a SharePoint site (2007 and 2010). In this form there is a repeating table with data that needs to be captured for reporting purposes. The solution I have chosen is to use the built in SharePoint lists.asmx Web Service to write the lines in the repeating table to a separate list on the sane SharePoint site, in the same site collection. I used the steps here, http://msdn.microsoft.com/en-us/library/cc162745(v=office.12).aspx, as my baseline.
I have gotten everything set up and working when run directly from the InfoPath form client site. The form opens and, on submit, the rows in the repeating table are written to the SharePoint list without any problems. However, once I deploy the form through Central Admin and test, none of the rows in the repeating table are getting written to the list. There are no errors or anything to indicate a problem with the code, and a boolean field used to indicate whether or not a row has been uploaded is set to true.
My first thought is that there is a problem with the permissions somewhere. Maybe when the service is called from client side it passes my credentials but when run from the server through the Document Library it's using something different? Shouldn't it use the credentials that are used to gain access to the SharePoint (which are also my AD credentials)? Is there a way to specify the use of the current users AD credentials when calling the lists.asmx web service in the code?
Anyway, not really sure where else to go with this. Any searching I do comes up with the same how two documentation on submitting to a SharePoint list in general. Any help would be greatly appreciated. Below is the code I am using to accomplish this.
if (MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:ShippingInformation/my:ShipDate", NamespaceManager).Value != "")
{
// If Ship Date is not blank, upload items in Material used to SP List where ForQuote is False
// Quote Number, RMA Number, Ship Date, Unit S/N,
// Create a WebServiceConnection object for submitting
// to the Lists Web service data connection.
WebServiceConnection wsSubmit =
(WebServiceConnection)this.DataConnections["Material Web Service Submit"];
//Create XPathNodeIterator object for the new Material Lines
XPathNodeIterator MaterialLines = this.MainDataSource.CreateNavigator().Select("/my:myFields/my:RepairQuote/my:QuoteLines/my:QuoteLine", NamespaceManager);
int lineCount = 0;
foreach (XPathNavigator NewLines in MaterialLines)
{
lineCount += 1;
if (NewLines.SelectSingleNode(".//my:ForQuote", NamespaceManager).Value == "false" && NewLines.SelectSingleNode(".//my:LineSubmitted", NamespaceManager).Value == "false")
{
// Set the values in the Add List Item Template
// XML file using the values in the new row.
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[#Name='Title']", NamespaceManager).SetValue(NewLines.SelectSingleNode(".//my:lineItem", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[#Name='RMANumber']", NamespaceManager).SetValue(MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:EntitlementContainer/my:RMANumber", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[#Name='UnitSerialNumber']", NamespaceManager).SetValue(MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:EntitlementContainer/my:serialNumber", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[#Name='ShipDate']", NamespaceManager).SetValue(MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:ShippingInformation/my:ShipDate", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[#Name='OrderType']", NamespaceManager).SetValue(MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:RepairQuote/my:orderType", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[#Name='QuoteNumber']", NamespaceManager).SetValue(MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:RepairQuote/my:quoteNumber", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[#Name='LineQuantity']", NamespaceManager).SetValue(NewLines.SelectSingleNode(".//my:lineQuantity", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[#Name='LineNumber']", NamespaceManager).SetValue(lineCount.ToString());
// Set the value of Cmd attribute to "New".
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/#Cmd", NamespaceManager).SetValue("New");
// Submit the new row.
wsSubmit.Execute();
NewLines.SelectSingleNode(".//my:LineSubmitted", NamespaceManager).SetValue("true");
}
}
}
I'm unsure why the code doesn't work when you deploy and call the lists web service in code. However I would suggest you to try debugging it to get to the root of the problem:
Step by Step – Debug InfoPath 2010 Forms Deployed on SharePoint 2010 Using Visual Studio 2010
Please try this out and step through it to see if it goes through the code as expected.
Well, I am not sure if it is the answer per se, but I believe the problem was related to security on the site. I got around this by using the SharePoint Object Model instead of the web service to create the list items (See http://www.bizsupportonline.net/browserforms/how-to-use-sharepoint-object-model-submit-data-infopath-browser-form-sharepoint-list.htm). With the SharePoint Object Model I am able to use AllowUnsafeUpdates. Also, where it took me quite a bit of time to get the web service set up, including the data connections, CAML file, etc. This way, however, only took a few minutes. Lesson learned, use the SharePoint Object Model if at all possible.
foreach (XPathNavigator NewLines in MaterialLines)
{
lineCount += 1;
if (NewLines.SelectSingleNode(".//my:ForQuote", NamespaceManager).Value == "false" && NewLines.SelectSingleNode(".//my:LineSubmitted", NamespaceManager).Value == "false")
{
using (SPSite site = SPContext.Current.Site)
{
if (site != null)
{
using (SPWeb web = site.OpenWeb())
{
// Turn on AllowUnsafeUpdates on the site
web.AllowUnsafeUpdates = true;
// Update the SharePoint list based on the values
// from the InfoPath form
SPList list = web.GetList("/Lists/InfoPathRtpItems");
if (list != null)
{
SPListItem item = list.Items.Add();
item["Title"] = NewLines.SelectSingleNode(".//my:lineItem", NamespaceManager).Value;
item["RMANumber"] = MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:EntitlementContainer/my:RMANumber", NamespaceManager).Value;
item["UnitSerialNumber"] = MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:EntitlementContainer/my:serialNumber", NamespaceManager).Value;
item["ShipDate"] = MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:ShippingInformation/my:ShipDate", NamespaceManager).Value;
item["OrderType"] = MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:RepairQuote/my:orderType", NamespaceManager).Value;
item["QuoteNumber"] = MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:RepairQuote/my:quoteNumber", NamespaceManager).Value;
item["LineQuantity"] = NewLines.SelectSingleNode(".//my:lineQuantity", NamespaceManager).Value;
item["LineNumber"] = lineCount.ToString();
item.Update();
}
// Turn off AllowUnsafeUpdates on the site
web.AllowUnsafeUpdates = false;
// Close the connection to the site
web.Close();
}
// Close the connection to the site collection
site.Close();
}
}
}
I've been given the task of content migration from another CMS system to SharePoint 2010.
The data in the old system is fairly easy to capture and the page hierarchy is simple so I'm not worried about that.
However, I am completely flummoxed about how to even create a page in code. I'm using the Microsoft.SharePoint.Client namespace as I do not have sharepoint installed on my system and am wanting to code this up as a console application and so I'm using I'm using ClientContext. (On the other hand, I am willing to go into other solutions if necessary).
My end-game: To get a page uploaded into some folder hierarchy which uses a master page, has the page title in a header web part, and a big ol' content-editable web part in the body so any user can come along and edit the content.
Things I've tried so far:
Using FileCollection.Add() to add an aspx file to the folder "Site Pages". This renders the html in the browser but doesn't enable any features for the user to edit the page
Using ListItemCollection.Add() to add a page to the site, but I didn't know what fields I needed. Also I remember it came up with a runtime error saying I should use FileCollection.Add()
Uploading to 'Site Pages' instead of 'Pages'
So many others... ow my head :(
The only plausible thing I can see on the net is to use the PublishingPage type along with PublishingWeb. However, PublishingWeb can only be constructed from an SPWeb object which requires me to be actually hosting the sharepoint application on my workstation.
If anyone can lend a hand that would be greatly appreciated :)
Here is a method I use to create pages. It seems a more supported way of creating pages than mr Aquino's. Though this is for MOSS 2007 I'm sure the equivalent exists in 2010. Also, I'd recommend to create console apps using the full object model. You'll have to run it on the server itself but that doesn't seem much of a problem for a migration? This way you won't be limited in any way.
public static void CreatePage(string url, string pageName, string title, string layoutName, Dictionary<string, string> fieldDataCollection)
{
var relUrl = new Uri(url);
using (SPSite site = new SPSite(url))
using (SPWeb web = site.AllWebs[relUrl.AbsolutePath])
{
if (!PublishingWeb.IsPublishingWeb(web))
throw new ArgumentException("The specified web is not a publishing web.");
PublishingWeb pubweb = PublishingWeb.GetPublishingWeb(web);
PageLayout layout = null;
string availableLayouts = string.Empty;
foreach (PageLayout lo in pubweb.GetAvailablePageLayouts())
{
availableLayouts += "\t" + lo.Name + "\r\n";
if (lo.Name.ToLowerInvariant() == layoutName.ToLowerInvariant())
{ layout = lo; break; }
}
if (layout == null)
throw new ArgumentException("The layout specified could not be found. Available layouts are:\r\n" + availableLayouts);
if (!pageName.ToLowerInvariant().EndsWith(".aspx")) pageName += ".aspx";
PublishingPage page = pubweb.GetPublishingPages().Add(pageName, layout);
page.Title = title;
SPListItem item = page.ListItem;
foreach (string fieldName in fieldDataCollection.Keys)
{
string fieldData = fieldDataCollection[fieldName];
try
{
SPField field = item.Fields.GetFieldByInternalName(fieldName);
if (field.ReadOnlyField)
{
Console.WriteLine("Field '{0}' is read only and will not be updated.", field.InternalName);
continue;
}
if (field.Type == SPFieldType.Computed)
{
Console.WriteLine("Field '{0}' is a computed column and will not be updated.", field.InternalName);
continue;
}
if (field.Type == SPFieldType.URL)
{
item[field.Id] = new SPFieldUrlValue(fieldData);
}
else if (field.Type == SPFieldType.User)
{
// AddListItem.SetUserField(web, item, field, fieldData);
}
else
{
item[field.Id] = fieldData;
}
}
catch (ArgumentException)
{
Console.WriteLine("WARNING: Could not set field {0} for item {1}.", fieldName, item.ID);
}
}
page.Update();
}
}
I don't see a way of creating a publishing page without the actual publishing methods.
When you create a new article page it will only create a few xml parameters inside the page, the layout itself lives in the /_catalogs/masterpage/article-XXXX.aspx file.
You can try downloading a native file created in the Pages document library, understand its structure, fill the XML with your data and then uploading it back to the Pages document library using the FileCollection -- that's my only guess.
Edit: sample Article Page
<%# Page Inherits="Microsoft.SharePoint.Publishing.TemplateRedirectionPage,Microsoft.SharePoint.Publishing,Version=12.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" %>
<%# Reference VirtualPath="~TemplatePageUrl" %>
<%# Reference VirtualPath="~masterurl/custom.master" %>
<html xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"><head>
<!--[if gte mso 9]><xml>
<mso:CustomDocumentProperties>
<mso:PublishingContact msdt:dt="string">1073741823</mso:PublishingContact>
<mso:display_urn_x003a_schemas-microsoft-com_x003a_office_x003a_office_x0023_PublishingContact msdt:dt="string">System Account</mso:display_urn_x003a_schemas-microsoft-com_x003a_office_x003a_office_x0023_PublishingContact>
<mso:PublishingContactPicture msdt:dt="string"></mso:PublishingContactPicture>
<mso:PublishingContactName msdt:dt="string"></mso:PublishingContactName>
<mso:ContentTypeId msdt:dt="string">0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF390078FB5FE740F6714B9595501175ECD8F000727044016EAB3B45B9E104498E366C85</mso:ContentTypeId>
<mso:Comments msdt:dt="string"></mso:Comments>
<mso:PublishingContactEmail msdt:dt="string"></mso:PublishingContactEmail>
<mso:PublishingPageLayout msdt:dt="string">http://dmserver008/_catalogs/masterpage/ArticlePage.aspx, EstudoAndre</mso:PublishingPageLayout>
</mso:CustomDocumentProperties>
</xml><![endif]--><title>New Article</title></head>
To grab one, hit the Pages library => Content Menu => Send To => Download a Copy
Uploading a page file should work, as long as you get the settings right on the item as well as the document itself. After you upload the file you can set the content type and properties appropriately. If you create a page manually first, you should be able to get an object that has all the right settings.
However, I would strongly recommend getting set up to develop a console app that will run on the sharepoint server rather than relying on the web services. The server side apis (including PublishingPage) tend to be a lot easier to work with.
I am using SharePiont Server 2007 Enterprise with Windows Server 2008 Enterprise, and I am using publishing portal template. I am developing using VSTS 2008 + C# + .Net 3.5. I want to know how to add a WebPart to all pages of a SharePoint Site? Any reference samples?
I want to use this WebPart to display some common information (but the information may change dynamically, and it is why I choose a WebPart) on all pages.
There are two ways to do this depending on your situation.
If the sites exist already, you need to iterate over the sites, adding the web part:
http://blogs.msdn.com/tconte/archive/2007/01/18/programmatically-adding-web-parts-to-a-page.aspx
If the sites do not exist then you can add the web part to the site template:
How to add a web part page to a site definition?
Here's the code from Shiraz's first link worked out a bit more:
(Note: This code is not optimized, for instance, looping through a List's Items collection is not something you should normally do, but seeing as this is probably a one time action there's no problem)
private void AddCustomWebPartToAllPages()
{
using(SPSite site = new SPSite("http://sharepoint"))
{
GetWebsRecursively(site.OpenWeb());
}
}
private void GetWebsRecursively(SPWeb web)
{
//loop through all pages in the SPWeb's Pages library
foreach(var item in web.Lists["Pages"].Items)
{
SPFile f = item.File;
SPLimitedWebPartManager wpm = f.GetLimitedWebPartManager(PersonalizationScope.Shared);
//ADD YOUR WEBPART
YourCustomWebPart wp = new YourCustomWebPart();
wp.YourCustomWebPartProperty = propertyValue;
wpm.AddWebPart(wp, "ZONEID", 1);
f.Publish("Added Web Part");
f.Approve("Web Part addition approved");
}
// now do this recursively
foreach(var subWeb in web.Webs)
{
GetWebsRecursively(subWeb);
}
web.Dispose();
}