Files
console_spo_utils/library_spo_utils/Services/SubSiteService.cs
T
2023-06-21 10:38:57 +02:00

114 lines
3.6 KiB
C#

using library_spo_utils.Constants;
using library_spo_utils.Interfaces.Services;
using Microsoft.Extensions.Logging;
using Microsoft.SharePoint.Client;
namespace library_spo_utils.Services;
internal class SubSiteService : ISubSiteService
{
private readonly ILogger<SubSiteService> logger;
private readonly IProjectQuickMenuService projectQuickMenuService;
public SubSiteService(ILogger<SubSiteService> logger,
IProjectQuickMenuService projectQuickMenuService)
{
this.logger = logger;
this.projectQuickMenuService = projectQuickMenuService;
}
public bool Create(string projName, ClientContext siteContext)
{
try
{
logger.LogInformation($"> Il sito {projName} è in fase di creazione!");
var wci = new WebCreationInformation
{
Url = projName,
Title = projName,
UseSamePermissionsAsParentSite = true,
WebTemplate = "SITEPAGEPUBLISHING#0"
};
var web = siteContext.Site.RootWeb.Webs.Add(wci);
siteContext.ExecuteQuery();
logger.LogInformation($"> Il sito {projName} è stato creato con successo!");
}
catch (Exception ex)
{
logger.LogError("Create Sub Site", ex);
return false;
}
return true;
}
public void AddColumnsToListView(string ssProjectTitle, ClientContext ctx)
{
try
{
var listTitle = $"SottoCommesse {ssProjectTitle}";
#region Field
logger.LogInformation($"> Inizializzata la fase di importazione dei campi in 'SottoCommesse {ssProjectTitle}'.");
var web = ctx.Web;
var list = web.Lists.GetByTitle(listTitle);
var siteField = ctx.Site.RootWeb;
ctx.Load(list, l => l.Fields);
ctx.Load(siteField, s => s.Fields);
ctx.ExecuteQuery();
AddFieldsToSubProj(siteField, list, ctx);
logger.LogInformation($"> Completata la fase di importazione dei campi in 'SottoCommesse {ssProjectTitle}'.");
#endregion
#region View
logger.LogInformation($"> Inizializzata la fase di creazione della ListView '{listTitle}'.");
var views = list.Views;
var viewCreation = new ViewCreationInformation
{
SetAsDefaultView = true,
Title = listTitle,
ViewTypeKind = ViewType.None,
ColumnWidth = "350",
ViewFields = Fields.SubProject
};
var view = views.Add(viewCreation);
ctx.Load(view);
ctx.ExecuteQuery();
logger.LogInformation($"> Completata la fase di creazione della ListView '{viewCreation.Title}'.");
var customView = views.GetByTitle(viewCreation.Title);
customView.MobileView = true;
customView.MobileDefaultView = true;
customView.Update();
ctx.ExecuteQuery();
logger.LogInformation($"> Abilitata la visualizzazione su mobile '{viewCreation.Title}'.");
#endregion
}
catch (Exception ex)
{
logger.LogError("Create Sub Site", ex);
}
}
private static void AddFieldsToSubProj(Web siteField, List list, ClientContext ctx)
{
foreach (var fieldName in Fields.SubSiteProject)
{
var fields = siteField.Fields.GetByInternalNameOrTitle(fieldName);
list.Fields.Add(fields);
}
ctx.ExecuteQuery();
}
}