How to add a content editor web part to a SharePoint page

Here is some code to add a content editor web part to a page. So if you are creating a page in code (like during feature activation), then you put a content editor web part on the page.

Setting the InnerText (contentXMLElement.InnerText = “”;) will set the text in the content editor, incase you want something to be there by default.  User HTML.

using (SPWeb webSite = SPContext.Current.Site.OpenWeb(SiteToOpen))
using (SPLimitedWebPartManager mgr = webSite.GetFile(“default.aspx”).GetLimitedWebPartManager(PersonalizationScope.Shared))
if (mgr != null)
# region AddNewLink

ContentEditorWebPart cewp = new ContentEditorWebPart();
cewp.AllowClose = false;
cewp.AllowEdit = false;
cewp.AllowHide = false;
cewp.AllowMinimize = false;
cewp.ID = “ContentEditorWP”;
cewp.Title = “Content Editor Web Part”;
cewp.ChromeType = PartChromeType.None;

//Add content to the content editor web part
XmlDocument addNewXMLDoc = new XmlDocument();
XmlElement contentXMLElement = addNewXMLDoc.CreateElement(“Root”);
contentXMLElement.InnerText = “”;
cewp.Content = contentXMLElement;
cewp.Content.InnerText = contentXMLElement.InnerText;

// add the web part.
// first argument: web part object
// second argument: zone
// third argument: index (location within the zone)
mgr.AddWebPart(cewp,”left”, 0);

# endregion


Detect who the current user in a SharePoint web part

It’s easy to detect who the current authenticated in ASP.HET (HttpContext.Current.User), but that doesn’t work in a web part.
So in a web part, you need to open a web and then you access the current user.

Below is an example (you just have to specify the “SiteToOpen”).


using (SPWeb webSite = SPContext.Current.Site.OpenWeb(SiteToOpen))
     //Determine who the current user is
        String currentUser = webSite.CurrentUser.Name;

.csharpcode, .csharpcode pre
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
background-color: #f4f4f4;
width: 100%;
margin: 0em;
.csharpcode .lnum { color: #606060; }


How to cache data in a SharePoint web part

Here is some sample code to cache a list of strings in a web part.

List<String> documentNames = new List<String>();
 object cacheddocumentNames = PartCacheRead(Storage.Shared, "DocumentNamesList");
 if (cacheddocumentNames != null)
       // cache exists, use it  
        documentNames = (List<String>)cacheddocumentNames as List<String>;