diff --git a/console_spo_utils/Program.cs b/console_spo_utils/Program.cs index 8a0761c..a43995d 100644 --- a/console_spo_utils/Program.cs +++ b/console_spo_utils/Program.cs @@ -15,44 +15,68 @@ using System.Web; 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 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 static async Task Main() { + #region SPO Credential string siteCollection = "https://italsortbuttrio.sharepoint.com"; string svcUser = "svcItsSharePointAdmin@italsort.com"; SecureString svcUserPsw = new NetworkCredential("", "$O,D1XBp1O5.OdjZt86#a=").SecurePassword; + #endregion - ProjectsByYearSite(siteCollection, svcUser, svcUserPsw); - Project(siteCollection, svcUser, svcUserPsw); - SubProject(siteCollection, svcUser, svcUserPsw); + #region General Variable + string year = DateTime.Now.Year.ToString(); + 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 ctx = authMgr.GetContext(site, user, psw)) { - try + if (SharePointCustomOperation.SiteExist(ctx) == false) { - if (SharePointCustomOperation.SiteExist(ctx) == false) - SharePointCustomOperation.ProjectsYSite(year, site, user, psw); - - if (SharePointCustomOperation.SiteExist(ctx) == true && SharePointCustomOperation.ListExist(year, ctx) == false) - { - SharePointCustomOperation.ProjectsYList(listTitle, ctx); - SharePointCustomOperation.ProjectsYListField(listTitle, ctx); - SharePointCustomOperation.ProjectsYListView(listTitle, ctx); - } - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); + SharePointCustomOperation.ProjectsYSite(year, site, user, psw); + //SharePointCustomOperation.ProjectsYField(ctx); + SharePointCustomOperation.ProjectsYList(listTitle, ctx); + SharePointCustomOperation.ProjectsYListField(listTitle, ctx); + SharePointCustomOperation.ProjectsYListView(listTitle, ctx); } } } @@ -67,23 +91,24 @@ namespace SharePointOnlineUtils Uri site = new Uri($"{siteCollection}/sites/{projectsYear}"); 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()) - using (var ctx = authMgr.GetContext(site, user, psw)) + if (SharePointCustomOperation.SiteExist(ctx) == true && SharePointCustomOperation.SiteExist(sCtx) == false) { - //if (SharePointCustomOperation.SiteExist(ctx)) //TODO: Controllo if sub site exist - SharePointCustomOperation.ProjectSubSite(ssProjectTitle, projectsYear, ctx); - SharePointCustomOperation.ProjectListEntry(ssProjectTitle, listTitle, projectsYear, ctx); + #region Site Context + SharePointCustomOperation.ProjectSubSite(ssProjectTitle, 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) @@ -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 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 { #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 { - List targetList = ctx.Web.Lists.GetByTitle("Lista Commesse " + year); + List targetList = ctx.Web.Lists.GetByTitle(listTitle); ctx.ExecuteQuery(); return true; } @@ -158,9 +161,55 @@ namespace SharePointOnlineUtils 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 - #region Projects by Years + #region Projects Years public static async Task ProjectsYSite(string year, Uri site, string user, SecureString psw) { Console.WriteLine($"> Inizializzata la fase di creazione del sito '../Commesse{year}'."); @@ -178,7 +227,7 @@ namespace SharePointOnlineUtils var scp = new SiteCreationProperties(); scp.Url = site.ToString(); - scp.Title = "Commesse " + year; + scp.Title = $"Commesse {year}"; scp.Owner = user; 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 fieldList = new Dictionary() + { + { "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", "", "", "", "", "", "", "", "", "", "", "" } } + }; + //"01 VENDITA MACCHINE / IMPIANTI02 VENDITA RICAMBI04 VENDITA SERVIZI FUORI COMMESSA08 VENDITA RIPARAZIONI09 ENGINEERING11 VENDITA E LAVORAZ.CONTO TERZI55 PREVENDITENC NON CONFORMITÁ" + foreach (KeyValuePair f in fieldList) + { + var fieldXml = $""; + 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) { try @@ -334,7 +415,7 @@ namespace SharePointOnlineUtils } #endregion - #region Project Page + #region Project public static async Task ProjectSubSite(string ssProjectTitle, string projectsYear, ClientContext ctx) { try @@ -455,15 +536,17 @@ namespace SharePointOnlineUtils #endregion } - public static async Task ProjectSubProjListField(string ssProjectTitle, ClientContext ctx) + public static async Task ProjectSubProjList(string ssProjectTitle, ClientContext ctx) { try { + var listTitle = $"SottoCommesse {ssProjectTitle}"; + #region Field Console.WriteLine($"> Inizializzata la fase di creazione dei campi in 'SottoCommesse {ssProjectTitle}'."); - + Web web = ctx.Web; - List list = web.Lists.GetByTitle($"SottoCommesse {ssProjectTitle}"); - List projectsList = web.Lists.GetByTitle($"SottoCommesse {ssProjectTitle}"); + List list = web.Lists.GetByTitle(listTitle); + List projectsList = web.Lists.GetByTitle(listTitle); ctx.Load(list, l => l.Fields); ctx.Load(projectsList, b => b.Id); @@ -477,24 +560,13 @@ namespace SharePointOnlineUtils ctx.ExecuteQuery(); Console.WriteLine($"> Completata la fase di creazione dei campi in 'SottoCommesse {ssProjectTitle}'."); - } - catch (Exception ex) - { - Console.WriteLine($"> Qualcosa è andato storto nella creazione delle colonne. ( {ex.Message} )"); - } - } + #endregion - public static async Task ProjectSubProjListView(string ssProjectTitle, ClientContext ctx) - { - try - { - var listTitle = $"SottoCommesse {ssProjectTitle}"; + #region View Console.WriteLine($"> Inizializzata la fase di creazione della ListView '{listTitle}'."); - List list = ctx.Web.Lists.GetByTitle(listTitle); var views = list.Views; - ViewCreationInformation viewCreation = new ViewCreationInformation(); viewCreation.SetAsDefaultView = true; @@ -518,10 +590,11 @@ namespace SharePointOnlineUtils ctx.ExecuteQuery(); Console.WriteLine($"> Abilitata la visualizzazione su mobile '{viewCreation.Title}'."); + #endregion } 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 { - #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.ExecuteQuery(); list.ContentTypesEnabled = true; list.Update(); - var documentCT = ctx.Site.RootWeb.AvailableContentTypes.GetById("0x0120D5"); - ctx.Load(documentCT); - ctx.ExecuteQuery(); - - var ctDocSet = new ContentTypeCreationInformation() + if (ListContentTypeExist(ctx, listTitle, "Set di documenti") == false) { - Name = "Set di documenti", - ParentContentType = documentCT - }; + var documentCT = ctx.Site.RootWeb.AvailableContentTypes.GetById("0x0120D5"); + 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(); - ctx.ExecuteQuery(); + list.Update(); + ctx.ExecuteQuery(); + } var ctData = list.ContentTypes.Where(c => c.Name == "Set di documenti"); var contentType = ctData.FirstOrDefault(); @@ -595,45 +672,48 @@ namespace SharePointOnlineUtils foreach (string spt in ssSubProjectTitle) { - Console.WriteLine($"> Inizializzata la fase di creazione per {spt}."); - - #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) + if (FolderExistsInsideList(ctx, listTitle, spt) == false) { - Console.WriteLine($"La sotto cartella {name} verrà creata in {spt}"); - var rPath = ResourcePath.FromDecodedUrl($"{spt}/{name}"); - list.RootFolder.AddSubFolderUsingPath(rPath); - } + Console.WriteLine($"> Inizializzata la fase di creazione per {spt}."); - ctx.ExecuteQuery(); + #region DocSet & Field value - Console.WriteLine($"Le sotto cartelle sono state create con successo in {spt}"); - #endregion + DocumentSet.Create(ctx, list.RootFolder, spt, contentType.Id); + 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)