Sharepoint 2010 - Create Site from Code using Custom Site Template - sharepoint

I am creating a NEW sharepoint site from a silverlight webpart. I am using the ClientContext Model and it is working great for a team site template (STS#0). I need to create a NEW site from a CUSTOM site template that I have created, but I do not know how to reference this template being to specify a web template it is by name and only able to reference one of the standard templates.
Here is my code:
string siteUrl = App.RootSite;
string siteDescription = project.projectName; // "A new project site.";
int projectLanguage = 1033;
string projectTitle = project.projectName; // "Project Web Site";
string projectUrl = project.projectURL; //"projectwebsite";
bool projectPermissions = false;
string webTemplate = "STS#0"; //TODO: reference custom site template
try
{
ClientContext clientContext = new ClientContext(siteUrl);
Web oWebsite = clientContext.Web;
WebCreationInformation webCreateInfo = new WebCreationInformation();
webCreateInfo.Description = siteDescription;
webCreateInfo.Language = projectLanguage;
webCreateInfo.Title = projectTitle;
webCreateInfo.Url = projectUrl;
webCreateInfo.UseSamePermissionsAsParentSite = projectPermissions;
webCreateInfo.WebTemplate = webTemplate;
oNewWebsite = oWebsite.Webs.Add(webCreateInfo);
clientContext.Load(
oNewWebsite,
website => website.ServerRelativeUrl,
website => website.Created,
website => website.Id);
clientContext.ExecuteQueryAsync(onQuerySucceeded, onQueryFail);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}

Loop through all of your available templates, you will find that the custom template name has the guid in front of it: {A13D0D34-EEC2-4BB5-A563-A926F7F9681A}#ProjectSiteTemplate.
ClientContext clientContext = new ClientContext(siteUrl);
Web oWebsite = clientContext.Web;
WebTemplateCollection templates = oWebsite.GetAvailableWebTemplates(1033, true);
clientContext.Load(templates);
clientContext.ExecuteQueryAsync(onTemplateSucceeded, null);
private void onTemplateSucceeded(object sender, ClientRequestSucceededEventArgs args)
{
UpdateUIMethod updateUI = ShowTemplates;
this.Dispatcher.BeginInvoke(updateUI);
}
private void ShowTemplates()
{
foreach (WebTemplate template in templates)
{
MessageBox.Show(template.Id + " : "
+ template.Name + " : "
+ template.Title);
}
}

example
http://www.learningsharepoint.com/2010/07/25/programatically-create-site-from-site-template-sharepoint-2010/

Related

Copying or moving files around in SharePoint Online

I see so many people struggling to copy or moving files around in SharePoint online, that I decided to write a small demo console app to show how to do it.
We will be using the CreateCopyJobs method, available on CSOM to copy a folder from one site collection to another. This method can be used to copy or move files between site collections or even on the same SC, betwen different libraries or folders inside a library.
The method works exactly as the UI, when you try to copy or move something in a library.
1 - Create new .NET console app. We will be using PnP, so go to your project NuGet manager and add SharePointPnPCoreOnline
2 - add to the usings of your class the following:
using Microsoft.SharePoint.Client;
using Newtonsoft.Json;
using OfficeDevPnP.Core;
3 - Define the following class to receive the status of the job that we will be checking.
class CopyJobProgress
{
public string Event;
public string JobId;
public string CorrelationId;
}
4 - Now add this sample main method:
static void Main(string[] args)
{
var siteUrl = "https://...-admin.sharepoint.com";
var userName = "admin#...";
var password = "....";
AuthenticationManager authManager = new AuthenticationManager();
using (var ctx = authManager.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
var web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
string sourceFile = "https://....sharepoint.com/sites/<site>/<library>/<file or folder>";
string destinationPath = "https://....sharepoint.com/sites/<site>/<destination library>";
var createJobInfo = ctx.Site.CreateCopyJobs(new string[] { sourceFile }, destinationPath,
new CopyMigrationOptions() { IsMoveMode = false, IgnoreVersionHistory = true,
AllowSchemaMismatch = true, NameConflictBehavior = MigrationNameConflictBehavior.Replace });
ctx.ExecuteQueryRetry();
Dictionary<string, CopyJobProgress> eventsFound = new Dictionary<string, CopyJobProgress>();
bool jobEndFound = false;
while (!jobEndFound)
{
var progress = ctx.Site.GetCopyJobProgress(createJobInfo[0]);
ctx.ExecuteQuery();
foreach (string log in progress.Value.Logs)
{
CopyJobProgress progressRes = (CopyJobProgress)JsonConvert.DeserializeObject(log, typeof(CopyJobProgress));
if (!eventsFound.ContainsKey(progressRes.Event))
{
Console.WriteLine(DateTime.Now + " - " + progressRes.Event + " - CorrelationId: " + progressRes.CorrelationId);
eventsFound[progressRes.Event] = progressRes;
}
if (progressRes.Event == "JobEnd")
{
jobEndFound = true;
}
}
if (!jobEndFound)
System.Threading.Thread.Sleep(2000);
}
Console.WriteLine("Done!");
}
}

Add document sharepoint using web service Microsoft Dynamics CRM

I have an account entity in my Microsoft Dynamics CRM and the every account I have folder in Sharepoint which contains documents of this account I want to create app on c# using Web Services CRM IOrganizationService to Add Documents in SharePoint.
it's possible ?
Please any links to do that.
I need to help.
thanks in advance
from your Question what is understood is that you have setup SharePoint in CRM Document Management System. You must have enabled Document Location for Accounts in the Document Management Settings. Now you want to Create/Upload documents to the Sharepoint Library. You can use Sharepoint: Client Side Object Model(CSOM) to do that. I have a piece of code that creates documents in sharepoint:
//Main Section Code
string sharePointUrl = GetDefaultSPSiteUrlFromCRMSiteCollectionEntity();
SharePointMethods sharePointMethods = new SharePointMethods(sharePointUrl, spUsername, spPassword, spDomain);
ClientContext context = sharePointMethods._clientContext;
Web web = sharePointMethods._clientContext.Web;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(newTempCRFDocumentFile);
newFile.Url = sharePointFolder.ServerRelativeUrl+ CRFfileGeneratedName;
newFile.Overwrite = true;
List docs = web.Lists.GetByTitle("Account");
Microsoft.SharePoint.Client.File uploadFile = sharePointFolder.Files.Add(newFile);
context.ExecuteQuery();
Helper Functions:
internal string GetDefaultSPSiteUrlFromCRMSiteCollectionEntity()
{
try
{
ConditionExpression c = new ConditionExpression("isdefault", ConditionOperator.Equal, true);
FilterExpression f = new FilterExpression(LogicalOperator.And);
f.Conditions.Add(c);
QueryExpression q = new QueryExpression("sharepointsite");
q.Criteria = f;
q.ColumnSet = new ColumnSet("sharepointsiteid", "name", "absoluteurl", "relativeurl", "isdefault", "parentsite");
EntityCollection crmSites = GRID.CRM.Common.Common.RetrieveMultiple(q);
if (crmSites.Entities.Count > 0)
{
Entity defaultSharePointSite = crmSites.Entities[0];
if (defaultSharePointSite.Attributes.Contains("parentsite") && defaultSharePointSite.Attributes.Contains("relativeurl"))
{
Entity parentSiteOfDefaultSite = GRID.CRM.Common.Common.RetrieveSingle("sharepointsite", ((EntityReference)defaultSharePointSite["parentsite"]).Id);
return (string)parentSiteOfDefaultSite["absoluteurl"] + "/" + defaultSharePointSite.GetAttributeValue<string>("relativeurl");
}
else
{
return defaultSharePointSite.GetAttributeValue<string>("absoluteurl");
}
}
// no SharePoint Sites defined in CRM
throw new Exception("CRM does not have any default SharePoint Sites");
}
catch (Exception ex)
{
throw new Exception("CrmMethods -> GetDefaultSPSite (" + ex.Message + ")");
}
}
internal class SharePointMethods
{
string _siteUrl;
public ClientContext _clientContext;
internal SharePointMethods(string spSiteUrl, string spUsername, string spPassword, string spDomain)
{
try
{
_siteUrl = spSiteUrl;
_clientContext = new ClientContext(_siteUrl);
_clientContext.Credentials = new System.Net.NetworkCredential
(spUsername, spPassword, spDomain);
}
catch (Exception ex)
{
throw new Exception("SharePointMethods.Constructor --> [" + ex.Message + "]");
}
}
}

How to add a Web Part into a SitePages/Home.aspx using CSOM

has anyone managed to add a Web Part into a Wiki page using CSOM?
Background: Home.aspx is a Wiki page and all its WPs are located in the rich text zone (in fact a "WikiField" column). Technically they are located in a hidden "wpz" web part zone and in addition to this there is always a placeholder with WP's ID in the WikiField column.
I've modified the existing server-side code seen on http://blog.mastykarz.nl/programmatically-adding-web-parts-rich-content-sharepoint-2010/ and http://640kbisenough.com/2014/06/26/sharepoint-2013-moving-webparts-programmatically-to-rich-content-zone/ into this:
using System;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.WebParts;
public class Class1
{
void DeployWebPart(ClientContext clientContext, string zone, string pattern, string position)
{
List library = clientContext.Web.GetList("/sites/site/SitePages/");
clientContext.Load(library);
clientContext.ExecuteQuery();
CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
ListItemCollection itemColl = library.GetItems(query);
clientContext.Load(itemColl, items => items.Include(i => i.Id, i => i.DisplayName, i => i["WikiField"]));
clientContext.ExecuteQuery();
ListItem item = itemColl.Where(i => i.DisplayName == "Home").First();
clientContext.ExecuteQuery();
File page = item.File;
LimitedWebPartManager lwm = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
string xmlWebPart = #"<webParts>...</webParts>";
WebPartDefinition wpd = lwm.ImportWebPart(xmlWebPart);
WebPartDefinition realWpd = lwm.AddWebPart(wpd.WebPart, "wpz", 0);
List targetList = clientContext.Web.GetList("/sites/site/Announcements/");
clientContext.Load(targetList, l => l.Views);
clientContext.Load(realWpd);
clientContext.ExecuteQuery();
string wpId = String.Format("g_{0}", realWpd.Id.ToString().Replace('-', '_'));
if (zone == "wpz")
{
string htmlcontent = String.Format(CultureInfo.InvariantCulture, "<div class=\"ms-rtestate-read ms-rte-wpbox\" contenteditable=\"false\"><div class=\"ms-rtestate-notify ms-rtestate-read {0}\" id=\"div_{0}\"></div><div id=\"vid_{0}\" style=\"display:none;\"></div></div>", new object[] { realWpd.Id.ToString("D") });
string content = item["WikiField"] as string;
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(System.Text.RegularExpressions.Regex.Escape(pattern));
if (position == "before")
{
content = regex.Replace(content, (htmlcontent + pattern), 1);
}
else
{
content = regex.Replace(content, (pattern + htmlcontent), 1);
}
item.Update();
clientContext.ExecuteQuery();
}
}
}
Everything works fine until the last item.Update() and clientContext.ExecuteQuery() are being invoked. Before the Update() the new placeholder gets properly inserted into the WikiField contents. But after the Update() the WikiField contents reverts back to its original state (!)
Note: As an alternative it is possible to add the WP into another zone (eg. "Bottom"). In this case the WP gets displayed on the page. But it has two major drawbacks: The newly created zone is not well formatted and the WP cannot be moved or even deleted.
Thanks for any input on this.
The following example demonstrates how to add web part into Enterprise Wiki page:
public static void AddWebPartIntoWikiPage(ClientContext context, string pageUrl, string webPartXml)
{
var page = context.Web.GetFileByServerRelativeUrl(pageUrl);
var webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
var importedWebPart = webPartManager.ImportWebPart(webPartXml);
var webPart = webPartManager.AddWebPart(importedWebPart.WebPart, "wpz", 0);
context.Load(webPart);
context.ExecuteQuery();
string marker = String.Format(CultureInfo.InvariantCulture, "<div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\"><div class=\"ms-rtestate-read {0}\" id=\"div_{0}\"></div><div style='display:none' id=\"vid_{0}\"></div></div>", webPart.Id);
ListItem item = page.ListItemAllFields;
context.Load(item);
context.ExecuteQuery();
item["PublishingPageContent"] = marker;
item.Update();
context.ExecuteQuery();
}
Usage
var webPartXml = System.IO.File.ReadAllText(filePath);
using (var ctx = new ClientContext(webUri))
{
AddWebPartIntoWikiPage(ctx, wikiPageUrl,webPartXml);
}
Result

SharePoint copying images from document library of a Web site to a document library in another Web site

I am moving image files from document library of a Web site to a document library in another Web site. I get the following error # line SPListItem oListItemDest = oFileDest.Item;
error:
[Microsoft.SharePoint.SPException] = {"The object specified does not belong to a list."}
Code:
try
{
using (SPSite oSiteCollectionSrc = new SPSite("http://dev:32223/"))
{
SPWeb oWebsiteSrc = oSiteCollectionSrc.AllWebs["en/people"];
SPList oListSrc = oWebsiteSrc.Lists["Images"];
SPListItemCollection collListItemsSrc = oListSrc.Items;
foreach (SPListItem oListItemSrc in collListItemsSrc)
{
SPFile oFileSrc = oListItemSrc.File;
Stream srcStream = oFileSrc.OpenBinaryStream();
using (SPSite oSiteCollectionDest = new SPSite("http://www.devmysites.com/"))
{
SPWeb oWebsiteDest = oSiteCollectionDest.OpenWeb("en/people");
SPList oListDest = oWebsiteDest.Lists["Images"];
SPFileCollection collFilesDest = oListDest.RootFolder.Files;
try
{
SPFile oFileDest = collFilesDest.Add(oListDest + #"/" + oFileSrc.Name, srcStream, true);
SPListItem oListItemDest = oFileDest.Item;
oListItemDest["Created"] = oFileDest.TimeCreated;
oListItemDest["Modified"] = oFileDest.TimeLastModified;
oListItemDest.Update();
}
catch(Exception es1)
{
Console.WriteLine("# Exception:#");
Console.WriteLine(es1.Message);
}
oWebsiteDest.Dispose();
}
}
oWebsiteSrc.Dispose();
}
}
catch (Exception es)
{
Console.WriteLine("# Exception:#");
Console.WriteLine(es.Message);
}
I have also had to copy documents between sharepoint lists, the code that I used to do it is in the answer to this question: SharePoint 2010: Copy documents between lists

Add/Create new document in SharePoint document Library programmatically

I have created a new Document Library and set up custom content type with MS Word Document Template. When i click on Create new template it works fine. but i need to be able to add some logic on a button event where it will go into that library and create a new document, so that when i go into that library i will see a new document that has been created by that button event.
i tried doing it as i would do a regular list item, but i got the following error on item.update:
To add an item to a document library, use SPFileCollection.Add()
Now i did some research but everywhere i see the code for uploading a file to the document library but no where i can find how to add a new document using my template that is associated in that doc library.
please help and thanks.
public static void colFileMtod()
{
using (SPSite objsite = new SPSite("http://smi-dev.na.sysco.net/SyscoFinance/FSR/"))
{
using (SPWeb objWeb = objsite.OpenWeb())
{
SPFileCollection collFiles = objWeb.GetFolder("BPCPublishRecord").Files;
SPList lst = objWeb.Lists["BPCPublishRecordCopy"];
if (lst != null)
{
if (objWeb.Lists.Cast<SPList>().Any(list => list.Title.Equals("BPCPublishRecordCopy", StringComparison.OrdinalIgnoreCase)))
{
foreach (SPFile file in collFiles)
{
string strDestUrl = collFiles.Folder.Url + "/" + file.Name;
byte[] binFile = file.OpenBinary();
SPUser oUserAuthor = file.Author;
SPUser oUserModified = file.ModifiedBy;
System.DateTime dtCreated = file.TimeCreated;
System.DateTime dtModified = file.TimeLastModified;
SPFile oFileNew = collFiles.Add(strDestUrl, binFile, oUserAuthor, oUserModified, dtCreated, dtModified);
SPListItem oListItem = lst.AddItem();
oListItem = oFileNew.Item;
oListItem["Created"] = dtCreated;
oListItem["Modified"] = dtModified;
oListItem.Update();
objWeb.AllowUnsafeUpdates = true;
}
}
}
}
}
}

Resources