This commit is contained in:
Kalarumeth
2022-07-28 08:03:42 +02:00
parent 5292d80586
commit 2a2879ccde
+209 -129
View File
@@ -15,44 +15,68 @@ using System.Web;
namespace SharePointOnlineUtils namespace SharePointOnlineUtils
{ {
public class ParentProj
{
public string ProjId { get; set; }
public string Description { get; set; }
public string Customer { get; set; }
public string DeliveryReason { get; set; }
public List<SubProj> SubProjects { get; set; }
}
public class SubProj
{
public string ProjId { get; set; }
public string Description { get; set; }
public string Customer { get; set; }
public string DeliveryReason { get; set; }
public string Position { get; set; }
public string ItemCode { get; set; }
public string ItemDescription { get; set; }
public string SerialNumber { get; set; }
}
public class Program public class Program
{ {
public static async Task Main() public static async Task Main()
{ {
#region SPO Credential
string siteCollection = "https://italsortbuttrio.sharepoint.com"; string siteCollection = "https://italsortbuttrio.sharepoint.com";
string svcUser = "svcItsSharePointAdmin@italsort.com"; string svcUser = "svcItsSharePointAdmin@italsort.com";
SecureString svcUserPsw = new NetworkCredential("", "$O,D1XBp1O5.OdjZt86#a=").SecurePassword; SecureString svcUserPsw = new NetworkCredential("", "$O,D1XBp1O5.OdjZt86#a=").SecurePassword;
#endregion
ProjectsByYearSite(siteCollection, svcUser, svcUserPsw); #region General Variable
Project(siteCollection, svcUser, svcUserPsw); string year = DateTime.Now.Year.ToString();
SubProject(siteCollection, svcUser, svcUserPsw); string projectsYear = $"Commesse{year}";
string listTitle = $"Lista Commesse {year}";
string ssProjectTitle = "CT0001";
string[] ssSubProjectTitle = { "CT0001-0001", "CT0001-0002", "CT0001-0003" };
Uri site = new Uri($"{siteCollection}/sites/{projectsYear}");
Uri subSite = new Uri($"{siteCollection}/sites/{projectsYear}/{ssProjectTitle}");
#endregion
SharePointCustomOperation.ProjectsYField();
//ProjectsByYearSite(listTitle, year, svcUser, site, svcUserPsw);
//Project(siteCollection, svcUser, svcUserPsw);
//SubProject(siteCollection, svcUser, svcUserPsw);
} }
public static async Task ProjectsByYearSite(string siteCollection, string user, SecureString psw) public static async Task ProjectsByYearSite(string listTitle, string year, string user, Uri site, SecureString psw)
{ {
string year = DateTime.Now.Year.ToString();
string projectsYear = "Commesse" + year;
string listTitle = "Lista Commesse " + year;
Uri site = new Uri(siteCollection + "/sites/" + projectsYear);
using (var authMgr = new AuthenticationManager()) using (var authMgr = new AuthenticationManager())
using (var ctx = authMgr.GetContext(site, user, psw)) using (var ctx = authMgr.GetContext(site, user, psw))
{ {
try if (SharePointCustomOperation.SiteExist(ctx) == false)
{ {
if (SharePointCustomOperation.SiteExist(ctx) == false) SharePointCustomOperation.ProjectsYSite(year, site, user, psw);
SharePointCustomOperation.ProjectsYSite(year, site, user, psw); //SharePointCustomOperation.ProjectsYField(ctx);
SharePointCustomOperation.ProjectsYList(listTitle, ctx);
if (SharePointCustomOperation.SiteExist(ctx) == true && SharePointCustomOperation.ListExist(year, ctx) == false) SharePointCustomOperation.ProjectsYListField(listTitle, ctx);
{ SharePointCustomOperation.ProjectsYListView(listTitle, ctx);
SharePointCustomOperation.ProjectsYList(listTitle, ctx);
SharePointCustomOperation.ProjectsYListField(listTitle, ctx);
SharePointCustomOperation.ProjectsYListView(listTitle, ctx);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
} }
} }
} }
@@ -67,23 +91,24 @@ namespace SharePointOnlineUtils
Uri site = new Uri($"{siteCollection}/sites/{projectsYear}"); Uri site = new Uri($"{siteCollection}/sites/{projectsYear}");
Uri subSite = new Uri($"{siteCollection}/sites/{projectsYear}/{ssProjectTitle}"); Uri subSite = new Uri($"{siteCollection}/sites/{projectsYear}/{ssProjectTitle}");
var authMgr = new AuthenticationManager();
var ctx = authMgr.GetContext(site, user, psw);
var sCtx = authMgr.GetContext(subSite, user, psw);
using (var authMgr = new AuthenticationManager()) if (SharePointCustomOperation.SiteExist(ctx) == true && SharePointCustomOperation.SiteExist(sCtx) == false)
using (var ctx = authMgr.GetContext(site, user, psw))
{ {
//if (SharePointCustomOperation.SiteExist(ctx)) //TODO: Controllo if sub site exist #region Site Context
SharePointCustomOperation.ProjectSubSite(ssProjectTitle, projectsYear, ctx); SharePointCustomOperation.ProjectSubSite(ssProjectTitle, projectsYear, ctx);
SharePointCustomOperation.ProjectListEntry(ssProjectTitle, listTitle, projectsYear, ctx); SharePointCustomOperation.ProjectListEntry(ssProjectTitle, listTitle, projectsYear, ctx);
#endregion
#region SubSite Context
SharePointCustomOperation.ProjectDocLib(ssProjectTitle, sCtx);
SharePointCustomOperation.ProjectSubProjList(ssProjectTitle, sCtx);
SharePointCustomOperation.ProjectQuickMenu(ssProjectTitle, subSite.ToString(), sCtx);
#endregion
} }
using (var authMgr = new AuthenticationManager())
using (var ctx = authMgr.GetContext(subSite, user, psw))
{
SharePointCustomOperation.ProjectDocLib(ssProjectTitle, ctx);
SharePointCustomOperation.ProjectSubProjListField(ssProjectTitle, ctx);
SharePointCustomOperation.ProjectSubProjListView(ssProjectTitle, ctx);
SharePointCustomOperation.ProjectQuickMenu(ssProjectTitle, subSite.ToString(), ctx);
}
} }
public static async Task SubProject(string siteCollection, string user, SecureString psw) public static async Task SubProject(string siteCollection, string user, SecureString psw)
@@ -105,28 +130,6 @@ namespace SharePointOnlineUtils
} }
public class ParentProj
{
public string ProjId { get; set; }
public string Description { get; set; }
public string Customer { get; set; }
public string DeliveryReason { get; set; }
public List<SubProj> SubProjects { get; set; }
}
public class SubProj
{
public string ProjId { get; set; }
public string Description { get; set; }
public string Customer { get; set; }
public string DeliveryReason { get; set; }
public string Position { get; set; }
public string ItemCode { get; set; }
public string ItemDescription { get; set; }
public string SerialNumber { get; set; }
}
public class SharePointCustomOperation public class SharePointCustomOperation
{ {
#region Check If Exist #region Check If Exist
@@ -145,11 +148,11 @@ namespace SharePointOnlineUtils
} }
} }
public static bool ListExist(string year, ClientContext ctx) public static bool ListExist(string listTitle, ClientContext ctx)
{ {
try try
{ {
List targetList = ctx.Web.Lists.GetByTitle("Lista Commesse " + year); List targetList = ctx.Web.Lists.GetByTitle(listTitle);
ctx.ExecuteQuery(); ctx.ExecuteQuery();
return true; return true;
} }
@@ -158,9 +161,55 @@ namespace SharePointOnlineUtils
return false; return false;
} }
} }
private static bool FolderExistsInsideList(ClientContext context, string listTitle ,string folderName)
{
var folderExists = context.Web.Lists.GetByTitle(listTitle).RootFolder;
context.Load(folderExists, f => f.Folders);
try
{
context.ExecuteQuery();
if (folderExists.Folders.Where(fn => fn.Name == folderName).Any())
{
return true;
}
return false;
}
catch (ServerUnauthorizedAccessException uae)
{
Console.WriteLine("You are not allowed to access this folder");
throw;
}
catch (Exception ex)
{
Console.WriteLine("Could not find folder.");
return false;
}
}
private static bool ListContentTypeExist(ClientContext ctx, string listTitle, string contentTypeName)
{
ContentTypeCollection cntCollection = ctx.Web.Lists.GetByTitle(listTitle).ContentTypes;
ctx.Load(cntCollection, cntyp => cntyp.Include(ct => ct.Name).Where(ct => ct.Name == contentTypeName));
ctx.ExecuteQuery();
if (!cntCollection.Any())
{
Console.WriteLine(cntCollection.Count);
return false;
}
else
{
Console.WriteLine(cntCollection.Count);
return true;
}
}
#endregion #endregion
#region Projects by Years #region Projects Years
public static async Task ProjectsYSite(string year, Uri site, string user, SecureString psw) public static async Task ProjectsYSite(string year, Uri site, string user, SecureString psw)
{ {
Console.WriteLine($"> Inizializzata la fase di creazione del sito '../Commesse{year}'."); Console.WriteLine($"> Inizializzata la fase di creazione del sito '../Commesse{year}'.");
@@ -178,7 +227,7 @@ namespace SharePointOnlineUtils
var scp = new SiteCreationProperties(); var scp = new SiteCreationProperties();
scp.Url = site.ToString(); scp.Url = site.ToString();
scp.Title = "Commesse " + year; scp.Title = $"Commesse {year}";
scp.Owner = user; scp.Owner = user;
scp.Template = "SITEPAGEPUBLISHING#0"; scp.Template = "SITEPAGEPUBLISHING#0";
@@ -205,6 +254,38 @@ namespace SharePointOnlineUtils
} }
} }
public static async Task ProjectsYField(ClientContext ctx)
{
try
{
var site = ctx.Site;
ctx.Load(site, w => w.RootWeb, w => w.RootWeb.Fields);
ctx.ExecuteQuery();
Dictionary<string, string[]> fieldList = new Dictionary<string, string[]>()
{
{ "PAL_ID_Project", new string[] { "Url", "ID Progretto", "", "", "", "", "", "", "", "", "", "" } },
{ "PAL_DlvReason", new string[] { "Choice", "", "", "", "", "", "", "", "", "", "", "" } },
{ "PAL_Customer", new string[] { "Text", "", "", "", "", "", "", "", "", "", "", "" } },
{ "PAL_Item", new string[] { "Text", "", "", "", "", "", "", "", "", "", "", "" } },
{ "PAL_ItemCode", new string[] { "Text", "", "", "", "", "", "", "", "", "", "", "" } },
{ "PAL_ItemDescription", new string[] { "Text", "", "", "", "", "", "", "", "", "", "", "" } },
{ "PAL_SerialNumber", new string[] { "Text", "", "", "", "", "", "", "", "", "", "", "" } }
};
//"<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>"
foreach (KeyValuePair<string, string[]> f in fieldList)
{
var fieldXml = $"<Field Name='{f.Key}' Type='{f.Value[0]}' Description='' DisplayName='{f.Value[1]}' StaticName='{f.Value[3]}' Group='{f.Value[4]}' Hidden='{f.Value[5]}' Required='{f.Value[6]}' Sealed='{f.Value[7]}' ShowInDisplayForm='{f.Value[8]}' ShowInEditForm='{f.Value[9]}' ShowInNewForm='{f.Value[10]}'>{f.Value[11]}</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} )"); }
}
public static async Task ProjectsYList(string listTitle, ClientContext ctx) public static async Task ProjectsYList(string listTitle, ClientContext ctx)
{ {
try try
@@ -334,7 +415,7 @@ namespace SharePointOnlineUtils
} }
#endregion #endregion
#region Project Page #region Project
public static async Task ProjectSubSite(string ssProjectTitle, string projectsYear, ClientContext ctx) public static async Task ProjectSubSite(string ssProjectTitle, string projectsYear, ClientContext ctx)
{ {
try try
@@ -455,15 +536,17 @@ namespace SharePointOnlineUtils
#endregion #endregion
} }
public static async Task ProjectSubProjListField(string ssProjectTitle, ClientContext ctx) public static async Task ProjectSubProjList(string ssProjectTitle, ClientContext ctx)
{ {
try try
{ {
var listTitle = $"SottoCommesse {ssProjectTitle}";
#region Field
Console.WriteLine($"> Inizializzata la fase di creazione dei campi in 'SottoCommesse {ssProjectTitle}'."); Console.WriteLine($"> Inizializzata la fase di creazione dei campi in 'SottoCommesse {ssProjectTitle}'.");
Web web = ctx.Web; Web web = ctx.Web;
List list = web.Lists.GetByTitle($"SottoCommesse {ssProjectTitle}"); List list = web.Lists.GetByTitle(listTitle);
List projectsList = web.Lists.GetByTitle($"SottoCommesse {ssProjectTitle}"); List projectsList = web.Lists.GetByTitle(listTitle);
ctx.Load(list, l => l.Fields); ctx.Load(list, l => l.Fields);
ctx.Load(projectsList, b => b.Id); ctx.Load(projectsList, b => b.Id);
@@ -477,24 +560,13 @@ namespace SharePointOnlineUtils
ctx.ExecuteQuery(); ctx.ExecuteQuery();
Console.WriteLine($"> Completata la fase di creazione dei campi in 'SottoCommesse {ssProjectTitle}'."); Console.WriteLine($"> Completata la fase di creazione dei campi in 'SottoCommesse {ssProjectTitle}'.");
} #endregion
catch (Exception ex)
{
Console.WriteLine($"> Qualcosa è andato storto nella creazione delle colonne. ( {ex.Message} )");
}
}
public static async Task ProjectSubProjListView(string ssProjectTitle, ClientContext ctx) #region View
{
try
{
var listTitle = $"SottoCommesse {ssProjectTitle}";
Console.WriteLine($"> Inizializzata la fase di creazione della ListView '{listTitle}'."); Console.WriteLine($"> Inizializzata la fase di creazione della ListView '{listTitle}'.");
List list = ctx.Web.Lists.GetByTitle(listTitle);
var views = list.Views; var views = list.Views;
ViewCreationInformation viewCreation = new ViewCreationInformation(); ViewCreationInformation viewCreation = new ViewCreationInformation();
viewCreation.SetAsDefaultView = true; viewCreation.SetAsDefaultView = true;
@@ -518,10 +590,11 @@ namespace SharePointOnlineUtils
ctx.ExecuteQuery(); ctx.ExecuteQuery();
Console.WriteLine($"> Abilitata la visualizzazione su mobile '{viewCreation.Title}'."); Console.WriteLine($"> Abilitata la visualizzazione su mobile '{viewCreation.Title}'.");
#endregion
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"> Qualcosa è andato storto nella creazione della ListView. ( {ex.Message} )"); Console.WriteLine($"> Qualcosa è andato storto... ( {ex.Message} )");
} }
} }
@@ -564,28 +637,32 @@ namespace SharePointOnlineUtils
{ {
try try
{ {
#region Context #region Context
var list = ctx.Web.Lists.GetByTitle($"SottoCommesse {ssProjectTitle}"); var listTitle = $"SottoCommesse {ssProjectTitle}";
var web = ctx.Web;
ctx.Load(web, w => w.Url);
var list = web.Lists.GetByTitle(listTitle);
ctx.Load(list, l => l.RootFolder, l => l.ContentTypes, l => l.Fields, l => l.ContentTypesEnabled); ctx.Load(list, l => l.RootFolder, l => l.ContentTypes, l => l.Fields, l => l.ContentTypesEnabled);
ctx.ExecuteQuery(); ctx.ExecuteQuery();
list.ContentTypesEnabled = true; list.ContentTypesEnabled = true;
list.Update(); list.Update();
var documentCT = ctx.Site.RootWeb.AvailableContentTypes.GetById("0x0120D5"); if (ListContentTypeExist(ctx, listTitle, "Set di documenti") == false)
ctx.Load(documentCT);
ctx.ExecuteQuery();
var ctDocSet = new ContentTypeCreationInformation()
{ {
Name = "Set di documenti", var documentCT = ctx.Site.RootWeb.AvailableContentTypes.GetById("0x0120D5");
ParentContentType = documentCT ctx.Load(documentCT);
}; ctx.ExecuteQuery();
list.ContentTypes.Add(ctDocSet); var ctDocSet = new ContentTypeCreationInformation()
{
Name = "Set di documenti",
ParentContentType = documentCT
};
list.ContentTypes.Add(ctDocSet);
list.Update(); list.Update();
ctx.ExecuteQuery(); ctx.ExecuteQuery();
}
var ctData = list.ContentTypes.Where(c => c.Name == "Set di documenti"); var ctData = list.ContentTypes.Where(c => c.Name == "Set di documenti");
var contentType = ctData.FirstOrDefault(); var contentType = ctData.FirstOrDefault();
@@ -595,45 +672,48 @@ namespace SharePointOnlineUtils
foreach (string spt in ssSubProjectTitle) foreach (string spt in ssSubProjectTitle)
{ {
Console.WriteLine($"> Inizializzata la fase di creazione per {spt}."); if (FolderExistsInsideList(ctx, listTitle, spt) == false)
#region DocSet & Field value
DocumentSet.Create(ctx, list.RootFolder, spt, contentType.Id);
ctx.ExecuteQuery();
Console.WriteLine($"> DocumentSet {spt} creata.");
var dsItem = list.RootFolder.Folders.GetByUrl(spt).ListItemAllFields;
dsItem["_ExtendedDescription"] = "valueDescription";
dsItem["Item"] = "valueItem";
dsItem["Codice_x0020_Articolo"] = "valueItemCode";
dsItem["Descrizione_x0020_Articolo"] = "valueItemDescription";
dsItem["Matricola_x0020_Macchina"] = "valueSerialNumber";
dsItem.Update();
ctx.ExecuteQuery();
Console.WriteLine($"> Field value update.");
#endregion
#region SubProject Folder
string[] folderName = { "09_Documenti_Tecnici", "12_Disegni_Costruttivi", "13_Manuali", "15_Documentazione_Elettrica", "16_Liste_Ricambi" };
foreach (string name in folderName)
{ {
Console.WriteLine($"La sotto cartella {name} verrà creata in {spt}"); Console.WriteLine($"> Inizializzata la fase di creazione per {spt}.");
var rPath = ResourcePath.FromDecodedUrl($"{spt}/{name}");
list.RootFolder.AddSubFolderUsingPath(rPath);
}
ctx.ExecuteQuery(); #region DocSet & Field value
Console.WriteLine($"Le sotto cartelle sono state create con successo in {spt}"); DocumentSet.Create(ctx, list.RootFolder, spt, contentType.Id);
#endregion ctx.ExecuteQuery();
Console.WriteLine($"> {spt} creato con successo in SottoCommesse {ssProjectTitle}."); Console.WriteLine($"> DocumentSet {spt} creata.");
var dsItem = list.RootFolder.Folders.GetByUrl(spt).ListItemAllFields;
dsItem["_ExtendedDescription"] = "valueDescription";
dsItem["Item"] = "valueItem";
dsItem["Codice_x0020_Articolo"] = "valueItemCode";
dsItem["Descrizione_x0020_Articolo"] = "valueItemDescription";
dsItem["Matricola_x0020_Macchina"] = "valueSerialNumber";
dsItem.Update();
ctx.ExecuteQuery();
Console.WriteLine($"> Field value update.");
#endregion
#region SubProject Folder
string[] folderName = { "09_Documenti_Tecnici", "12_Disegni_Costruttivi", "13_Manuali", "15_Documentazione_Elettrica", "16_Liste_Ricambi" };
foreach (string name in folderName)
{
Console.WriteLine($"La sotto cartella {name} verrà creata in {spt}");
var rPath = ResourcePath.FromDecodedUrl($"{spt}/{name}");
list.RootFolder.AddSubFolderUsingPath(rPath);
}
ctx.ExecuteQuery();
Console.WriteLine($"Le sotto cartelle sono state create con successo in {spt}");
#endregion
Console.WriteLine($"> {spt} creato con successo in SottoCommesse {ssProjectTitle}.");
}
} }
} }
catch (Exception ex) catch (Exception ex)