Define Field

WP test
This commit is contained in:
Kalarumeth
2022-08-30 18:01:56 +02:00
parent ba397104a7
commit 948add6d0c
+145 -299
View File
@@ -2,10 +2,12 @@
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.DocumentSet;
using Microsoft.SharePoint.Client.WebParts;
using PnP.Core.Model.SharePoint;
using System;
//using PnP.Core.Model.SharePoint;
//using PnP.Core.Services;
using System.Collections.Concurrent;
using System.Drawing.Text;
using System.Net;
using System.Reflection.PortableExecutable;
using System.Security;
@@ -54,7 +56,7 @@ namespace SharePointOnlineUtils
#region General Variable
string year = DateTime.Now.Year.ToString();
string varProjSiteName = $"Commesse {year}";
string projectsYear = $"{varProjSiteName.Replace(" ", string.Empty)}";
string projectsYear = varProjSiteName.Replace(" ", string.Empty);
string listTitle = $"Lista {varProjSiteName}";
string ssProjectTitle = "CT0016";
string[] ssSubProjectTitle = { "CT0016-0001", "CT0016-0002", "CT0016-0003" };
@@ -65,12 +67,12 @@ namespace SharePointOnlineUtils
#region Project
//ProjectsByYearSite(listTitle, varProjSiteName, svcUser, site, svcUserPsw);
//Project(siteCollection, svcUser, svcUserPsw);
Project(siteCollection, svcUser, svcUserPsw);
//SubProject(siteCollection, svcUser, svcUserPsw);
#endregion
#region Offer
Offer(siteCollection, svcUser, svcUserPsw);
//Offer(siteCollection, svcUser, svcUserPsw);
#endregion
}
@@ -83,12 +85,12 @@ namespace SharePointOnlineUtils
if (spc.SiteExist(ctx) == false)
{
spc.TenantCreation(varProjSiteName, site, user, psw);
spc.DomainGroupRights(ctx, string.Empty);
spc.OnenoteSPFeature(ctx, string.Empty, string.Empty);
spc.ProjectsYField(ctx);
spc.ProjectsYList(listTitle, ctx);
spc.ProjectsYListView(listTitle, ctx);
//spc.TenantCreation(varProjSiteName, site, user, psw);
//spc.DomainGroupRights(ctx, string.Empty);
//spc.OnenoteSPFeature(ctx, string.Empty, string.Empty);
//spc.PalCustomField(ctx, spc.FieldType.Project);
//spc.ProjectsYList(listTitle, ctx);
//spc.ProjectsYListView(listTitle, ctx);
}
}
}
@@ -107,20 +109,22 @@ namespace SharePointOnlineUtils
var ctx = authMgr.GetContext(site, user, psw);
var sCtx = authMgr.GetContext(subSite, user, psw);
if (spc.SiteExist(ctx) == true && spc.SiteExist(sCtx) == false)
{
#region Site Context
spc.ProjectSubSite(ssProjectTitle, projectsYear, ctx);
spc.OnenoteSPFeature(ctx, year, ssProjectTitle);
spc.ProjectListEntry(ssProjectTitle, listTitle, projectsYear, ctx);
#endregion
spc.AddWebPart(ctx, "/sites/Commesse2022/CT0008/SitePages/homepage.aspx");
#region SubSite Context
spc.ProjectDocLib(ssProjectTitle, sCtx);
spc.ProjectSubProjList(ssProjectTitle, sCtx);
spc.ProjectQuickMenu(ssProjectTitle, subSite.ToString(), sCtx);
#endregion
}
//if (spc.SiteExist(ctx) == true && spc.SiteExist(sCtx) == false)
//{
// #region Site Context
// spc.ProjectSubSite(ssProjectTitle, projectsYear, ctx);
// spc.OnenoteSPFeature(ctx, year, ssProjectTitle);
// spc.ProjectListEntry(ssProjectTitle, listTitle, projectsYear, ctx);
// #endregion
//
// #region SubSite Context
// spc.ProjectDocLib(ssProjectTitle, sCtx);
// spc.ProjectSubProjList(ssProjectTitle, sCtx);
// spc.ProjectQuickMenu(ssProjectTitle, subSite.ToString(), sCtx);
// #endregion
//}
}
public static async Task SubProject(string siteCollection, string user, SecureString psw)
@@ -136,7 +140,7 @@ namespace SharePointOnlineUtils
using (var authMgr = new AuthenticationManager())
using (var ctx = authMgr.GetContext(subSite, user, psw))
{
if ( spc.SiteExist(ctx) )
if (spc.SiteExist(ctx))
spc.SubProjectDocSet(ssProjectTitle, ssSubProjectTitle, ctx);
}
}
@@ -154,21 +158,30 @@ namespace SharePointOnlineUtils
var authMgr = new AuthenticationManager();
var ctx = authMgr.GetContext(site, user, psw);
if ( spc.SiteExist(ctx) == false) // Inutile
{
spc.TenantCreation(tenantName, site, user, psw);
}
if ( spc.SiteExist(ctx) && spc.ListExist(ctx, docLibName) == false )
{
//spc.OfferDocLib(year, ctx);
}
//if (spc.SiteExist(ctx) == false)
//{
// spc.TenantCreation(tenantName, site, user, psw);
// spc.PalCustomField(ctx, spc.FieldType.Quotation);
//}
//if (spc.SiteExist(ctx) && spc.ListExist(ctx, docLibName) == false)
//{
// spc.ProjectsYField(ctx, source);
// spc.OfferDocLib(year, ctx);
//}
}
#endregion
}
public class SharePointCustomOperation
{
public enum FieldType
{
Project,
Quotation
}
#region Check If Exist
public static bool SiteExist(ClientContext ctx)
{
@@ -199,7 +212,7 @@ namespace SharePointOnlineUtils
}
}
public static bool FolderExistsInsideList(ClientContext context, string listTitle ,string folderName)
public static bool FolderExistsInsideList(ClientContext context, string listTitle, string folderName)
{
var folderExists = context.Web.Lists.GetByTitle(listTitle).RootFolder;
context.Load(folderExists, f => f.Folders);
@@ -308,31 +321,51 @@ namespace SharePointOnlineUtils
}
#region Projects Years
public static async Task ProjectsYField(ClientContext ctx)
public static async Task PalCustomField(ClientContext ctx, FieldType et)
{
Dictionary<string, string[]> fieldList = new Dictionary<string, string[]>()
Dictionary<string, string[]> fieldList = new Dictionary<string, string[]>();
switch (et)
{
{ "PAL_ID_Project", new string[] { "URL", "ID Progetto", "PAL Field", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } },
{ "PAL_DlvReason", new string[] { "Choice", "Causale", "PAL Field", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", "TRUE", "<CHOICES><CHOICE>01 VENDITA MACCHINE / IMPIANTI</CHOICE><CHOICE>02 VENDITA RICAMBI</CHOICE><CHOICE>04 VENDITA SERVIZI FUORI COMMESSA</CHOICE><CHOICE>08 VENDITA RIPARAZIONI</CHOICE><CHOICE>09 ENGINEERING</CHOICE><CHOICE>11 VENDITA E LAVORAZ.CONTO TERZI</CHOICE><CHOICE>55 PREVENDITE</CHOICE><CHOICE>NC NON CONFORMITÁ</CHOICE></CHOICES>" } },
{ "PAL_Customer", new string[] { "Text", "Cliente", "PAL Field", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } },
{ "PAL_Item", new string[] { "Text", "Item", "PAL Field", "FALSE", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } },
{ "PAL_ItemCode", new string[] { "Text", "Codice Articolo", "PAL Field", "FALSE", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } },
{ "PAL_ItemDescription", new string[] { "Text", "Descrizione Articolo", "PAL Field", "FALSE", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } },
{ "PAL_SerialNumber", new string[] { "Text", "Matricola Macchina", "PAL Field", "FALSE", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } }
};
case FieldType.Project:
fieldList = new Dictionary<string, string[]>()
{
{ "PAL_ID_Project", new string[] { "URL", "ID Progetto", "PAL Field", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } },
{ "PAL_DlvReason", new string[] { "Choice", "Causale", "PAL Field", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", "TRUE", "<CHOICES><CHOICE>01 VENDITA MACCHINE / IMPIANTI</CHOICE><CHOICE>02 VENDITA RICAMBI</CHOICE><CHOICE>04 VENDITA SERVIZI FUORI COMMESSA</CHOICE><CHOICE>08 VENDITA RIPARAZIONI</CHOICE><CHOICE>09 ENGINEERING</CHOICE><CHOICE>11 VENDITA E LAVORAZ.CONTO TERZI</CHOICE><CHOICE>55 PREVENDITE</CHOICE><CHOICE>NC NON CONFORMITÁ</CHOICE></CHOICES>" } },
{ "PAL_Customer", new string[] { "Text", "Cliente", "PAL Field", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } },
{ "PAL_Item", new string[] { "Text", "Item", "PAL Field", "FALSE", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } },
{ "PAL_ItemCode", new string[] { "Text", "Codice Articolo", "PAL Field", "FALSE", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } },
{ "PAL_ItemDescription", new string[] { "Text", "Descrizione Articolo", "PAL Field", "FALSE", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } },
{ "PAL_SerialNumber", new string[] { "Text", "Matricola Macchina", "PAL Field", "FALSE", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } }
};
break;
case FieldType.Quotation:
fieldList = new Dictionary<string, string[]>()
{
{ "PAL_Offers_Reason", new string[] { "Choice", "Causale", "PAL Field", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", "TRUE", $"<CHOICES><CHOICE>01 VENDITA MACCHINE / IMPIANTI</CHOICE><CHOICE>02 VENDITA RICAMBI</CHOICE><CHOICE>04 VENDITA SERVIZI FUORI COMMESSA</CHOICE><CHOICE>08 VENDITA RIPARAZIONI</CHOICE><CHOICE>09 ENGINEERING</CHOICE><CHOICE>11 VENDITA E LAVORAZ.CONTO TERZI</CHOICE><CHOICE>55 PREVENDITE</CHOICE><CHOICE>NC NON CONFORMITÁ</CHOICE></CHOICES>" } },
{ "PAL_ID_Quotation", new string[] { "Text", "ID Offerta", "PAL Field", "FALSE", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } },
{ "PAL_Quotation_Name", new string[] { "Text", "Fornitore", "PAL Field", "FALSE", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } },
{ "PAL_Authors", new string[] { "Text", "Autore", "PAL Field", "FALSE", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } }
};
break;
default:
throw new NotImplementedException("Entity type not found");
}
try
{
var site = ctx.Site;
ctx.Load(site, w => w.RootWeb, w => w.RootWeb.Fields);
ctx.ExecuteQuery();
foreach (KeyValuePair<string, string[]> f in fieldList)
if (fieldList != null)
{
var fieldXml = $"<Field Name='{f.Key}' Type='{f.Value[0]}' Description='' DisplayName='{f.Value[1]}' StaticName='{f.Key}' Group='{f.Value[2]}' Hidden='{f.Value[3]}' Required='{f.Value[4]}' Sealed='{f.Value[5]}' ShowInDisplayForm='{f.Value[6]}' ShowInEditForm='{f.Value[7]}' ShowInNewForm='{f.Value[8]}'>{f.Value[9]}</Field>";
site.RootWeb.Fields.AddFieldAsXml(fieldXml, false, AddFieldOptions.AddToDefaultContentType);
ctx.Load(site.RootWeb.Fields);
var site = ctx.Site;
ctx.Load(site, w => w.RootWeb, w => w.RootWeb.Fields);
ctx.ExecuteQuery();
foreach (KeyValuePair<string, string[]> f in fieldList)
{
var fieldXml = $"<Field Name='{f.Key}' Type='{f.Value[0]}' Description='' DisplayName='{f.Value[1]}' StaticName='{f.Key}' Group='{f.Value[2]}' Hidden='{f.Value[3]}' Required='{f.Value[4]}' Sealed='{f.Value[5]}' ShowInDisplayForm='{f.Value[6]}' ShowInEditForm='{f.Value[7]}' ShowInNewForm='{f.Value[8]}'>{f.Value[9]}</Field>";
site.RootWeb.Fields.AddFieldAsXml(fieldXml, false, AddFieldOptions.AddToDefaultContentType);
ctx.Load(site.RootWeb.Fields);
}
}
ctx.ExecuteQuery();
@@ -522,8 +555,6 @@ namespace SharePointOnlineUtils
{ $"Commerciale {ssProjectTitle}", (int)ListTemplateType.DocumentLibrary },
};
//string[] docLibName = { $"Documenti {ssProjectTitle}", $"Media {ssProjectTitle}", $"SottoCommesse {ssProjectTitle}", $"Commerciale {ssProjectTitle}" };
foreach (KeyValuePair<string, Int32> kvp in docLibNames)
{
Console.WriteLine($"> Inizializzata la fase di creazione '{kvp.Key}'.");
@@ -533,7 +564,7 @@ namespace SharePointOnlineUtils
ListCreationInformation lci = new ListCreationInformation();
lci.Title = kvp.Key;
lci.TemplateType = kvp.Value; //(int)ListTemplateType.DocumentLibrary; // TO-DO: PictureLibrary x Media
lci.TemplateType = kvp.Value;
List list = web.Lists.Add(lci);
ctx.ExecuteQuery();
@@ -542,9 +573,9 @@ namespace SharePointOnlineUtils
Console.WriteLine($"> '{kvp.Key}' è stato creato con successo.");
}
#endregion
#endregion
#region Dir
#region Dir
Dictionary<string, string> folderName = new Dictionary<string, string>
{
{ "01_Costificazioni", $"Commerciale {ssProjectTitle}" },
@@ -558,7 +589,7 @@ namespace SharePointOnlineUtils
};
foreach (KeyValuePair<string, string> kvp in folderName)
{
{
Console.WriteLine($"> Inizializzata la fase di {kvp.Key} in {kvp.Value}.");
List list = ctx.Web.Lists.GetByTitle(kvp.Value);
@@ -591,7 +622,7 @@ namespace SharePointOnlineUtils
Web web = ctx.Web;
List list = web.Lists.GetByTitle(listTitle);
var siteField = ctx.Site.RootWeb ;
var siteField = ctx.Site.RootWeb;
ctx.Load(list, l => l.Fields);
ctx.Load(siteField, s => s.Fields);
@@ -733,7 +764,7 @@ namespace SharePointOnlineUtils
if (FolderExistsInsideList(ctx, listTitle, spt) == false)
{
Console.WriteLine($"> Inizializzata la fase di creazione per {spt}.");
#region DocSet Field Entry
DocumentSet.Create(ctx, list.RootFolder, spt, contentType.Id);
ctx.ExecuteQuery();
@@ -763,7 +794,7 @@ namespace SharePointOnlineUtils
var rPath = ResourcePath.FromDecodedUrl($"{spt}/{name}");
list.RootFolder.AddSubFolderUsingPath(rPath);
}
ctx.ExecuteQuery();
Console.WriteLine($"Le sotto cartelle sono state create con successo in {spt}");
@@ -771,7 +802,7 @@ namespace SharePointOnlineUtils
Console.WriteLine($"> {spt} creato con successo in SottoCommesse {ssProjectTitle}.");
}
}
}
}
catch (Exception ex)
{
@@ -782,42 +813,6 @@ namespace SharePointOnlineUtils
#endregion
#region Offer
public static async Task OfferSite() // TODO: Da creare?? contiene la base di crazione del tenant e le impostazioni base in caso devesse essere cancellata
{
}
public static async Task OfferField(ClientContext ctx)
{
try
{
Dictionary<string, string[]> fieldList = new Dictionary<string, string[]>()
{
{ "PAL_Offers_Reason", new string[] { "Choice", "Causale", "PAL Field", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", "TRUE", $"<CHOICES><CHOICE>01 VENDITA MACCHINE / IMPIANTI</CHOICE><CHOICE>02 VENDITA RICAMBI</CHOICE><CHOICE>04 VENDITA SERVIZI FUORI COMMESSA</CHOICE><CHOICE>08 VENDITA RIPARAZIONI</CHOICE><CHOICE>09 ENGINEERING</CHOICE><CHOICE>11 VENDITA E LAVORAZ.CONTO TERZI</CHOICE><CHOICE>55 PREVENDITE</CHOICE><CHOICE>NC NON CONFORMITÁ</CHOICE></CHOICES>" } },
{ "PAL_Customer", new string[] { "Text", "Cliente", "PAL Field", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } },
{ "PAL_ID_Offer", new string[] { "Text", "Codice Articolo", "PAL Field", "FALSE", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } },
{ "PAL_Offers_Name", new string[] { "Text", "Item", "PAL Field", "FALSE", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } },
{ "PAL_Authors", new string[] { "Text", "Descrizione Articolo", "PAL Field", "FALSE", "FALSE", "TRUE", "TRUE", "TRUE", "TRUE", string.Empty } }
};
var site = ctx.Site;
ctx.Load(site, w => w.RootWeb, w => w.RootWeb.Fields);
ctx.ExecuteQuery();
foreach (KeyValuePair<string, string[]> f in fieldList)
{
var fieldXml = $"<Field Name='{f.Key}' Type='{f.Value[0]}' Description='' DisplayName='{f.Value[1]}' StaticName='{f.Key}' Group='{f.Value[2]}' Hidden='{f.Value[3]}' Required='{f.Value[4]}' Sealed='{f.Value[5]}' ShowInDisplayForm='{f.Value[6]}' ShowInEditForm='{f.Value[7]}' ShowInNewForm='{f.Value[8]}'>{f.Value[9]}</Field>";
site.RootWeb.Fields.AddFieldAsXml(fieldXml, false, AddFieldOptions.AddToDefaultContentType);
ctx.Load(site.RootWeb.Fields);
}
ctx.ExecuteQuery();
}
catch (Exception ex)
{ Console.WriteLine($"!> Qualcosa è andato storto... ( {ex.Message} )"); return; }
}
public static async Task OfferDocLib(string year, ClientContext ctx)
{
try
@@ -859,8 +854,8 @@ namespace SharePointOnlineUtils
{ Console.WriteLine($"!> Qualcosa è andato storto... {ex.Message}"); return; }
}
public static async Task OfferDocSet(string year, ClientContext ctx)
{
public static async Task OfferDocSet(string year, ClientContext ctx)
{
try
{
var listTitle = $"Offerte {year}";
@@ -900,7 +895,7 @@ namespace SharePointOnlineUtils
#endregion
#region SPFeature
public static async Task OnenoteSPFeature(ClientContext ctx, string year, string ssProjectTitle)
public static async Task OnenoteSPFeature(ClientContext ctx, string year, string ssProjectTitle) //TODO: predisposizione per offerte
{
var featureName = "SiteNotebook";
Guid featureId = new Guid("f151bb39-7c3b-414f-bb36-6bf18872052f");
@@ -1023,219 +1018,70 @@ namespace SharePointOnlineUtils
#endregion
#region WebParts
public static void AddWebPart(ClientContext ctx, string siteUrl)
{
try
{
Web web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
//public static void WebPartPage(ClientContext ctx, string sitePath, string ssProjectTitle)
//{
// var homeLocation = $"{sitePath}/SitePages/Home.aspx";
// string[] listName = { $"Documenti {ssProjectTitle}", $"Media {ssProjectTitle}", $"SottoCommesse {ssProjectTitle}", $"Commerciale {ssProjectTitle}" };
SP.File oFile = ctx.Web.GetFileByServerRelativeUrl(siteUrl);
LimitedWebPartManager limitedWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);
// try
// {
// foreach (string item in listName)
// {
string webPartXml = //"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<WebPart xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" + " xmlns=\"http://schemas.microsoft.com/WebPart/v2\">" + "<Title>My Web Part</Title><FrameType>Default</FrameType>" + "<Description>Use for formatted text, tables, and images.</Description>" + "<IsIncluded>true</IsIncluded><ZoneID></ZoneID><PartOrder>0</PartOrder>" + "<FrameState>Normal</FrameState><Height /><Width /><AllowRemove>true</AllowRemove>" + "<AllowZoneChange>true</AllowZoneChange><AllowMinimize>true</AllowMinimize>" + "<AllowConnect>true</AllowConnect><AllowEdit>true</AllowEdit>" + "<AllowHide>true</AllowHide><IsVisible>true</IsVisible><DetailLink /><HelpLink />" + "<HelpMode>Modeless</HelpMode><Dir>Default</Dir><PartImageSmall />" + "<MissingAssembly>Cannot import this Web Part.</MissingAssembly>" + "<PartImageLarge>/_layouts/images/mscontl.gif</PartImageLarge><IsIncludedFilter />" + "<Assembly>Microsoft.SharePoint, Version=13.0.0.0, Culture=neutral, " + "PublicKeyToken=94de0004b6e3fcc5</Assembly>" + "<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>" + "<ContentLink xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\" />" + "<Content xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\">" + "<![CDATA[This is a first paragraph!<DIV> </DIV>And this is a second paragraph.]]></Content>" + "<PartStorage xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\" /></WebPart>";
"<?xml version='1.0' encoding=\"utf-8\"?>" +
"<webParts>" +
"<webPart xmlns='http://schemas.microsoft.com/WebPart/v3'>" +
"<metaData>" +
"<type name='Microsoft.SharePoint.WebPartPages.XsltListViewWebPart, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' />" +
"<importErrorMessage>Cannot import this Web Part.</importErrorMessage>" +
"</metaData>" +
"<data>" +
"<properties>" +
"<property name='ListUrl' type='string' />" +
"<property name='ListId' type='System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'>757981FB-184A-441B-952D-9434BE33DC85</property>" +
"<property name='ListName' type='string'>{757981FB-184A-441B-952D-9434BE33DC85}</property>" +
"</properties>" +
"</data>" +
"</webPart>" +
"<webPart>" +
"<ContentLink xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\" />" +
"<Content xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\">" +
"<![CDATA[This is my test text!" +
"<DIV>&nbsp;</DIV>" +
"<DIV>Blah blah blah</DIV>" +
"<DIV>&nbsp;</DIV>" +
"<DIV>And another blah</DIV>]]>" +
"</Content><PartStorage xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\" />" +
"</webPart>" +
"</webParts>";
// List list = ctx.Web.Lists.GetByTitle(item);
// ctx.Load(list, l => l.Id);
// ctx.ExecuteQuery();
// //Console.WriteLine(viewList);
// //AddWebPart(ctx, homeLocation, viewList.HtmlSchemaXml);
// }
// }
// catch (Exception ex) { Console.WriteLine($"!> Qualcosa è andato storto... ( {ex.Message} {ex.StackTrace} )"); return; }
//}
WebPartDefinition oWebPartDefinition = limitedWebPartManager.ImportWebPart(webPartXml);
limitedWebPartManager.AddWebPart(oWebPartDefinition.WebPart, "Left", 1);
ctx.ExecuteQuery();
}
catch (Exception ex) { Console.WriteLine($"!> Qualcosa è andato storto... ( {ex.Message} )\n[\n{ex.StackTrace}\n]"); return; }
}
//private static void CreateWebPartPage(this SPWeb web, List list, string pageName, int layoutTemplate)
//{
// const string newWPPage = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
// "<Batch>" +
// "<Method ID=\"0,NewWebPage\">" +
// "<SetList Scope=\"Request\">{0}</SetList>" +
// "<SetVar Name=\"Cmd\">NewWebPage</SetVar>" +
// "<SetVar Name=\"ID\">New</SetVar>" +
// "<SetVar Name=\"Type\">WebPartPage</SetVar>" +
// "<SetVar Name=\"WebPartPageTemplate\">{2}</SetVar>" +
// "<SetVar Name=\"Overwrite\">true</SetVar>" +
// "<SetVar Name=\"Title\">{1}</SetVar>" +
// "</Method>" +
// "</Batch>";
// var newWPPageBatchXml = string.Format(newWPPage, list.Id, pageName, layoutTemplate);
// var result = web.ProcessBatchData(newWPPageBatchXml);
//}
//public static void AddWebPart(ClientContext context, string pageUrl, string xml)
//{
// try
// {
// Console.WriteLine("Start");
// var page = context.Web.GetFileByUrl(pageUrl);
// var webpartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
// context.Load(webpartManager, w => w.WebParts);
// context.ExecuteQuery();
// WebPartDefinition webpartDef = webpartManager.ImportWebPart(xml);
// WebPartDefinition webpart = webpartManager.AddWebPart(webpartDef.WebPart, "mainContent", 0);
// context.Load(webpartDef);
// context.ExecuteQuery();
// //webpartManager.ImportWebPart(xmlWP);
// //context.ExecuteQuery();
// Console.WriteLine("End");
// }
// catch (Exception ex) { Console.WriteLine($"!> Qualcosa è andato storto... ( {ex.Message} {ex.StackTrace} )"); return; }
//}
//protected void ReplaceWebPartsWithAppParts(ClientContext ctx)
//{
// Web web = ctx.Web;
// // Get properties from the Web.
// ctx.Load(web,
// w => w.ServerRelativeUrl,
// w => w.AllProperties);
// ctx.ExecuteQuery();
// // Read the Pages library name from the Web properties.
// var pagesListName = web.AllProperties["__pageslistname"] as string;
// var list = web.Lists.GetByTitle(pagesListName);
// var items = list.GetItems(CamlQuery.CreateAllItemsQuery());
// // Get the file associated with each list item.
// ctx.Load(items, i => i.Include(item => item.File));
// ctx.ExecuteQuery();
// // Iterate through all pages in the Pages list.
// foreach (var item in items)
// {
// FindWebPartToReplace(item, ctx, web);
// }
//}
//private static void FindWebPartToReplace(ListItem item, ClientContext clientContext, Web web)
//{
// SP.File page = item.File;
// // Requires Full Control permissions on the Web.
// string oldWebPartTitle = "";
// LimitedWebPartManager webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
// clientContext.Load(webPartManager,
// wpm => wpm.WebParts,
// wpm => wpm.WebParts.Include(
// wp => wp.WebPart.Title));
// clientContext.ExecuteQuery();
// foreach (var oldWebPartDefinition in webPartManager.WebParts)
// {
// var oldWebPart = oldWebPartDefinition.WebPart;
// // Modify the web part if we find an old web part with the same title.
// if (oldWebPart.Title != oldWebPartTitle) continue;
// ReplaceWebPart(web, item, webPartManager, oldWebPartDefinition, clientContext, page);
// }
//}
//private static void ReplaceWebPart(Web web, ListItem item, LimitedWebPartManager webPartManager, WebPartDefinition oldWebPartDefinition, ClientContext clientContext, SP.File page)
//{
// string appPartXml = "";
// // Create a web part definition using the XML string.
// var definition = webPartManager.ImportWebPart(appPartXml);
// webPartManager.AddWebPart(definition.WebPart, "RightColumn", 0);
// // Delete the old web part from the page.
// oldWebPartDefinition.DeleteWebPart();
// clientContext.Load(page,
// p => p.CheckOutType,
// p => p.Level);
// clientContext.ExecuteQuery();
//}
//public static void WebPartPage(ClientContext ctx)
//{
// try
// {
// ClientSidePage pageWebParts = ctx.Web.AddClientSidePage("PageWithSections.aspx", true);
// pageWebParts.AddSection(CanvasSectionTemplate.OneColumnFullWidth, 5);
// pageWebParts.Save();
// var components = pageWebParts.AvailableClientSideComponents();
// var webPartToAdd = components.Where(wp => wp.ComponentType == 1 && wp.Name == "MYWEBPARTNAME").FirstOrDefault();
// if (webPartToAdd != null)
// {
// ClientSideWebPart clientWp = new ClientSideWebPart(webPartToAdd) { Order = 1 };
// pageWebParts.AddControl(clientWp, pageWebParts.Sections[0].Columns[2]);
// }
// pageWebParts.Save();
// ctx.ExecuteQuery();
// }
// catch (Exception ex) { Console.WriteLine($"!> Qualcosa è andato storto... ( {ex.Message} )\n[\n{ex.StackTrace}\n]"); return; }
//}
//private static void AddWebPart(Web web, LimitedWebPartManager mgr, string listName, string zoneName, int zoneId)
//{
// var webPartXml =
// "<?xml version='1.0' encoding=\"utf-8\"?>" +
// "<webParts>" +
// "<webPart xmlns='http://schemas.microsoft.com/WebPart/v3'>" +
// "<metaData>" +
// "<type name='Microsoft.SharePoint.WebPartPages.XsltListViewWebPart, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' />" +
// "<importErrorMessage>Cannot import this Web Part.</importErrorMessage>" +
// "</metaData>" +
// "<data>" +
// "<properties>" +
// "<property name='ListUrl' type='string' />" +
// "<property name='ListId' type='System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'>757981FB-184A-441B-952D-9434BE33DC85</property>" +
// "<property name='ListName' type='string'>{757981FB-184A-441B-952D-9434BE33DC85}</property>" +
// "</properties>" +
// "</data>" +
// "</webPart>" +
// "<webPart>" +
// "<ContentLink xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\" />" +
// "<Content xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\">" +
// "<![CDATA[This is my test text!" +
// "<DIV>&nbsp;</DIV>" +
// "<DIV>Blah blah blah</DIV>" +
// "<DIV>&nbsp;</DIV>" +
// "<DIV>And another blah</DIV>]]>" +
// "</Content><PartStorage xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\" />" +
// "</webPart>" +
// "</webParts>";
// WebPart importingWebPart = mgr.ImportWebPart(webPartXml).WebPart; // take webPartXml from above
// WebPartDefinition wpDefinition = mgr.AddWebPart(importingWebPart, "Top", 1);
// mgr.Context.Load(wpDefinition,
// d => d.Id); // Id of the hidden view which gets automatically created
// mgr.Context.ExecuteQuery();
// var viewId = wpDefinition.Id;
// List list = web.Lists.GetByTitle("MyLibrary");
// View view = list.Views.GetById(viewId);
// view.ViewFields.RemoveAll();
// view.ViewFields.Add("Title");
// view.ViewQuery = "<Where><Eq><FieldRef Name=\"Title\" /><Value Type=\"Text\">Something Here</Value></Eq></Where>";
// view.RowLimit = 10;
// web.Context.ExecuteQuery();
//}
public static void GetWebPart(ClientContext ctx)
{
Web web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
}
#endregion
}
public class AuthenticationManager : IDisposable
{
private static readonly HttpClient httpClient = new HttpClient();
private const string tokenEndpoint = "https://login.microsoftonline.com/common/oauth2/token";
private const string defaultAADAppId = "46e6296e-176f-4ebb-a14b-bdd5678c16e6";
private static readonly SemaphoreSlim semaphoreSlimTokens = new SemaphoreSlim(1);
private AutoResetEvent tokenResetEvent = null;
private readonly ConcurrentDictionary<string, string> tokenCache = new ConcurrentDictionary<string, string>();