Taylohtio/CondoUpdate/CondoUpdate.AddResponsibleU.../UpdaterImpl.cs

104 lines
3.0 KiB
C#

using System;
using System.IO;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Taloyhtio.CondoUpdate.Common;
namespace CondoUpdate.AddResponsibleUserField
{
public class UpdaterImpl : ICondoUpdater
{
public event EventHandler<LogEventArgs> OnNotify;
public void Update(object args)
{
string url = args as string;
if (string.IsNullOrEmpty(url))
{
this.warn("Url is empty");
return;
}
try
{
this.updateImpl(url);
}
catch (Exception x)
{
this.error("Error occured during updating of Condo '{0}':\n{1}\n{2}", url, x.Message, x.StackTrace);
}
}
private void updateImpl(string url)
{
using (var site = new SPSite(url))
{
var web = site.RootWeb;
var list = web.Lists.Cast<SPList>().FirstOrDefault(l => string.Compare(l.Title, "Sivustot", true) == 0);
if (list == null)
{
warn("List not found");
return;
}
string fieldTitle = "Isännöitsijä FBA";
if (!list.Fields.Cast<SPField>().Any(f => f.Title == fieldTitle))
{
string internalName = list.Fields.Add(fieldTitle, SPFieldType.User, false);
addFieldIntoDefaultView(list, internalName);
}
}
}
private void addFieldIntoDefaultView(SPList list, string internalName)
{
var field = list.Fields.Cast<SPField>().FirstOrDefault(i => i.InternalName == internalName || i.StaticName == internalName);
if (field == null)
{
return;
}
try
{
var view = list.DefaultView;
var viewFields = view.ViewFields;
viewFields.Add(field);
view.Update();
}
catch (Exception x)
{
error("Exception occured: {0}\n{1}", x.Message);
}
}
private void info(string msg, params object[] args)
{
this.notify(LogLevel.Info, msg, args);
}
private void warn(string msg, params object[] args)
{
this.notify(LogLevel.Warn, msg, args);
}
private void error(string msg, params object[] args)
{
this.notify(LogLevel.Error, msg, args);
}
private void notify(LogLevel level, string msg, params object[] args)
{
this.notify(level, string.Format(msg, args));
}
private void notify(LogLevel level, string msg)
{
if (this.OnNotify != null)
{
this.OnNotify(this, new LogEventArgs { LogLevel = level, Message = msg });
}
}
}
}