How to get data from web part in sandbox solution Sharepoint 2010 - sharepoint

I want to get data from web part using sharepoint workflow to fill list item data. How can I solve this problem using sandbox solution?
I found how that can be done using farm solution but not sandbox:
using (SPSite site = new SPSite(""))
{
using (SPWeb web = site.OpenWeb())
{
SPFile file = web.GetFile("default.aspx");
SPLimitedWebPartManager lwpm = file.GetLimitedWebPartManager(PersonalizationScope.Shared); SPLimitedWebPartCollection webParts = lwpm.WebParts;
System.Web.UI.WebControls.WebParts.WebPart wp = webParts[1];
string content = (((Microsoft.SharePoint.WebPartPages.ContentEditorWebPart)(wp)).Content).InnerText;
}
}

Related

SharePoint Directories/Files

I have a need that for a given sharepoint site, which i have read access to, i need to find out all the list/count of subdirectories & files. The folders go down 3-4 levels.
I have gone through this website for some options -
https://www.softvative.com/blog/2015/02/four-ways-to-get-report-of-sharepoint-folders-and-files-for-a-library/
Still not able to get a list, can anyone suggest a simple way to get that.
Thanks.
The following C# code for your reference.
using (SPSite site = new SPSite("http://sp2013/sites/team"))
{
using (SPWeb web = site.OpenWeb())
{
SPListCollection docLibraryColl = web.GetListsOfType(SPBaseType.DocumentLibrary);
foreach (SPList list in docLibraryColl)
{
Console.WriteLine("-------------LibraryName:" + list.Title + "--------------");
//get all folders in the library
SPListItemCollection oFolders = list.Folders;
//get all files in the library
SPQuery query = new SPQuery();
query.ViewAttributes = "Scope=\"Recursive\"";
var files=list.GetItems(query);
Console.WriteLine("Folder Count:"+oFolders.Count+" | File Count:"+files.Count);
}
}
}

When trying to get all webparts on a Sharepoint Online page using C# CSOM, I get 0 returned (while there *are* webparts on my page)

So I'm using C# CSOM code to try and get all webparts, so that I can remove one. My Sharepoint Online page is just a standard modern teamsite page with nothing changed yet. I want to get all webparts, then remove the quick links standard webpart using csom. Here's my code:
Microsoft.SharePoint.Client.File oFile =
Context.Web.GetFileByServerRelativeUrl("/sites/CR-WST-GYM-20130306/SitePages/Home.aspx");
LimitedWebPartManager wpManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);
/*Context.Load(wpManager.WebParts,
wps => wps.Include(
wp => wp.WebPart.Title));*/
Context.Load(wpManager);
Context.ExecuteQueryRetry();
WebPartDefinitionCollection wpDefinitionCollection = wpManager.WebParts;
Context.Load(wpDefinitionCollection);
Context.ExecuteQueryRetry();
It loads, but wpManager.WebParts contains 0 values & has a count of 0... how is this possible, when there's already standard webparts added to a newly created teamsite? Shouldn't I get at least a couple? What might I be doing wrong?
This code is taken from: https://learn.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ee539301(v%3Doffice.14) .
EDIT: I've also added a new webpart via UI to my main page to see if I get "1" as value, but it's still 0 ...
For "modern" site pages OfficeDevPnP.Core.Pages namespace has been introduced to manage web parts instead of Microsoft.SharePoint.Client.WebParts namespace
The following example demonstrates how to retrieve the list of client-side web parts on page
using (var ctx = new ClientContext(webUrl))
{
ctx.Credentials = GetCredentials(userName, password);
var page = OfficeDevPnP.Core.Pages.ClientSidePage.Load(ctx, "Home.aspx");
var webParts = page.Controls.Where(c => c.Type.Name == "ClientSideWebPart").ToList();
}
Prerequisites
SharePointPnPCoreOnline package
Reference
Customizing "modern" site pages
PnP isn't needed. This is working for me.
CamlQuery allPagesQuery = new CamlQuery();
ListItemCollection pageItems = list.GetItems(allPagesQuery);
ctx.Load(pageItems, pi => pi.Include(i => i.Id, i => i.DisplayName));
ctx.ExecuteQuery();
foreach (var item in pageItems)
{
ctx.Load(item, i => i.File, i => i.File.ServerRelativeUrl);
ctx.ExecuteQuery();
LimitedWebPartManager wpManager =
item.File.GetLimitedWebPartManager(PersonalizationScope.Shared);
ctx.Load(wpManager, wpm => wpm.WebParts.Include(wp => wp.WebPart.Title, wp => wp.Id));
ctx.ExecuteQuery();
foreach (WebPartDefinition wp in wpManager.WebParts)
{
log4.DebugFormat("Webpart in {0}: {1} [{2}]",
item.File.ServerRelativeUrl, wp.WebPart.Title, wp.Id);
}
}

Creating new site collection in Office 365 from an APP

I have a requirement to create a new site collection from within an App in Office 365 programmatically. What I mean by a new site collection, is that after creation, it should appear on the list of site collections under the Admin --> Sharepoint tab of Office 365. I tried using a similar code below within a sharepoint hosted app that i had created,
//create sp context and get root
var clientContext = new SP.ClientContext.get_current();
var rootWeb = clientContext.site.rootWeb();
this.clientContext.load(rootWeb);
this.clientContext.executeQUery();
//set web info
var webInfo = new SP.WebCreationInformation();
webInfo.set_webTemplate('YourTemplateName');
webInfo.set_description('Your site description');
webInfo.set_title('Your site tittle');
webInfo.set_url(siteUrl);
webInfo.set_language(yourLangCode);
this.rootWeb.get_webs().add(webInfo);
this.rootWeb.update();
// save site and set callbacks
this.clientContext.load(this.rootWeb);
this.clientContext.executeQueryAsync(
Function.createDelegate(this, this.OnSiteCreationSuccess),
Function.createDelegate(this, this.Error));
However this just creates a sub site under the site collection that hosts my App.
Any suggestions on how i could implement this would be greatly appreciated.
It can be done with SharePoint Object Model 2013, the functions you need are inside the assembly: Microsoft.Online.SharePoint.Client.Tenant.dll, which is located at C:\Program Files\SharePoint Client Components\Assemblies after you install the SharePoint Client Object model 2013.
There's not much doc on this, but SharePoint Online Management Shell has the command to create the site collection, so I think it can be done with C# and figured it out. The code snippet shows how to do it.
using System;
using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.SharePoint.Client;
using System.Security;
namespace SharePoint123
{
class Program
{
static void Main(string[] args)
{
//please change the value of user name, password, and admin portal URL
string username = "xxxx#xxxx.onmicrosoft.com";
String pwd = "xxxx";
ClientContext context = new ClientContext("https://xxxx-admin.sharepoint.com");
SecureString password = new SecureString();
foreach (char c in pwd.ToCharArray())
{
password.AppendChar(c);
}
context.Credentials = new SharePointOnlineCredentials(username, password);
Tenant t = new Tenant(context);
context.ExecuteQuery();//login into SharePoint online
//code to create a new site collection
var newsite = new SiteCreationProperties()
{
Url = "https://xxxxx.sharepoint.com/sites/createdbyProgram1",
Owner = "xxxxx#xxxxx.onmicrosoft.com",
Template = "STS#0", //using the team site template, check the MSDN if you want to use other template
StorageMaximumLevel = 100,
UserCodeMaximumLevel = 100,
UserCodeWarningLevel = 100,
StorageWarningLevel = 300,
Title = "CreatedbyPrgram",
CompatibilityLevel = 15, //15 means Shapoint online 2013, 14 means Sharepoint online 2010
};
t.CreateSite(newsite);
context.ExecuteQuery();
//end
}
}
}

Programmatically insert a List as a webpart in a webpart page in WSS 3.0

I tried searching on the net to programmatically insert a List as a webpart in a webpart page but was not lucky enough.
Any thoughts or ideas how i could Programmatically insert a List as a webpart in a webpart page
Many Thanks!
First add these using statements.
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
Then in your code
// First get the list
SPSite site = new SPSite("http://myserver");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["MyCustomlist"];
// Create a webpart
ListViewWebPart wp = new ListViewWebPart();
wp.ZoneID = "Top"; // Replace this ith the correct zone on your page.
wp.ListName = list.ID.ToString("B").ToUpper();
wp.ViewGuid = list.DefaultView.ID.ToString("B").ToUpper();
// Get the web part collection
SPWebPartCollection coll =
web.GetWebPartCollection("default.aspx", // replace this with the correct page.
Storage.Shared);
// Add the web part
coll.Add(wp);
If you want to use a custom view, try playing with this:
SPView view = list.GetUncustomizedViewByBaseViewId(0);
wp.ListViewXml = view.HtmlSchemaXml;
Hope it helps,
W0ut
You need to perform two steps to add a web part to a page. First you have to create the list you want to show on the page. Therefore you can use the Add() method of the web site's list collection (SPListCollection).
To show the list on the web part page you have to add a ListViewWebPart to the web part page using the SPLimitedWebPartManager of the page.
To make this more re-usable as part of a feature receiver, you could pass in the splist and spview as part of a method:
static public void AddEventsListViewWebPart(PublishingPage page, string webPartZoneId, int zoneIndex, string webPartTitle, PartChromeType webPartChromeType, string listName, string viewname)
{
using (SPLimitedWebPartManager wpManager = page.ListItem.File.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
SPWeb web = page.PublishingWeb.Web;
SPList myList = web.Lists.TryGetList(listName);
using (XsltListViewWebPart lvwp = new XsltListViewWebPart())
{
lvwp.ListName = myList.ID.ToString("B").ToUpperInvariant();
lvwp.Title = webPartTitle;
// Specify the view
SPView view = myList.Views[viewname];
lvwp.ViewGuid = view.ID.ToString("B").ToUpperInvariant();
lvwp.TitleUrl = view.Url;
lvwp.Toolbar = "None";
lvwp.ChromeType = webPartChromeType;
wpManager.AddWebPart(lvwp, webPartZoneId, zoneIndex);
}
}
}
And then call it during feature activation:
AddEventsListViewWebPart(welcomePage, "Right", 1, "Events", PartChromeType.TitleOnly, "Events", "Calendar");

Can I programmatically replace one webpart with another in Sharepoint?

Edit: This is a decade old so very likely not to be relevant to anyone, if google has brought you here I would be sceptical of the content against more modern frameworks!
We have a sharepoint website that has been quite heavily developed with content using the out of the box content editor webpart. This is a bit rubbish when it comes to using any other browser than IE.
We have in mind to update to the free Telerik content editor, however we would like to save ourselves a large amount of copy and pasting, and clicking and selecting to swap the web parts over.
There seems to be no official upgrade path but it seems to me that it must be possible to use the power of code (tm) to grab the content of the original webpart, new up a telerik webopart and put the content into the new webpart... then delete the old original web part.
Has anyone done this sort of thing? How is it best to lay out the code and actually run the code that will do the swap (if it is possible). A fresh webpart with a "Do Swap" button on? or something more sophisticated?
I also would need to walk through every page and subsite (and page in subsite) and look at every web part. Is there a best practice way of doing this?
I would write a console application for this.
Open the root Web and iterate through its sub webs.
Do the work needed for each page, by opening the WebPartManager.
Here are some pseudo code to get you started.
string SourceUrl = "http://ThisWeb";
using (SPSite sourceSite = new SPSite(SourceURL))
{
using (SPWeb sourceWeb = sourceSite.OpenWeb(SourceURL))
{
IterateSubWebsProd(sourceWeb):
}
}
private void IterateSubWebsProd(SPWeb sourceWeb)
{
// This is the migration function
DoThingyWithThisWeb(sourceWeb);
foreach (SPWeb subWeb in sourceWeb.Webs)
{
IterateSubWebsProd(subWeb);
subWeb.Dispose();
}
}
private void DoThingyWithThisWeb(SPWeb sourceWeb)
{
PublishingPage currentPage = null;
string currentPageName = "<something>";
// Find the pages that you want to modify, with a CAML query for example
SPQuery query = new SPQuery();
query.Query = string.Format("" +
"<Where>" +
"<Eq>" +
"<FieldRef Name='FileLeafRef' />" +
"<Value Type='File'>{0}</Value>" +
"</Eq>" +
"</Where>" +
"", currentPageName);
// This codesnippet is from a Publishing web example
PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(sourceWeb);
PublishingPageCollection pageColl = publishingWeb.GetPublishingPages(query);
if (pageColl.Count > 0)
{
currentPage = pageColl[0];
}
using (SPLimitedWebPartManager wpMan = currentPage.ListItem.File.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
{
foreach (WebPart wp in wpMan.WebParts)
{
if (wp.GetType().Equals(typeof(Microsoft.SharePoint.WebPartPages.ContentEditorWebPart)))
{
Microsoft.SharePoint.WebPartPages.ContentEditorWebPart thisWebPart = wp as Microsoft.SharePoint.WebPartPages.ContentEditorWebPart;
// This is just dummy code, here you will do your content migration
XmlDocument xmlDoc = new XmlDocument();
XmlElement xmlElement = xmlDoc.CreateElement("RootElement");
xmlElement.InnerText = sourceItem[SourceField].ToString();
thisWebPart.Content = xmlElement;
wpMan.SaveChanges(thisWebPart);
}
}
}
}
I'm not 100% certain on this, but if your content is saved into a list as individual fields, could you not point the Telerik controls at where that content is saved? This may cause Telerik controls to freak out a bit on the first edit of that content, but they should be ok to re-format the content and recover.

Resources