如果在数据库中插入新记录,如何更新 SharePoint Online 列表?
How to update a SharePoint Online list if a new record is inserted in the database?
我有一个保存个人信息的 MySQL 数据库。每当雇用新员工时 he/she 填写一些个人信息,这些数据就会存储在 table.
中
经过一些研究(因为我无法访问其他系统 - 只有数据库),计划是构建一个 C# 控制台应用程序来检索数据并根据 SharePoint 列表检查它。如果以前 SharePoint 列表中不存在的数据库中有新记录,我想更新列表(创建新项目)。
请注意,如果 SharePoint 列表包含更多列,则 table 包含额外的手动信息。
我已经发布了针对数据库的连接代码以及我如何检索数据。
如何检查项目是否存在于 SharePoint 列表中?有人能提供一个答案,其中包括用于创建和插入新项目的代码吗?我有两列(在数据库和 SP 列表中)可以用作主键。
有一个支持 CRUD 的 REST API,所以我想这应该是一个明智的选择。
SharePoint 列表:
using System;
using System.Windows;
public class DbConnection
{
private String databaseName;
private String serverAddress;
private String pwd;
private String userName;
private Boolean connected;
private MySql.Data.MySqlClient.MySqlConnection conn;
public DbConnection(String databaseName, String serverAddress, String pwd, String userName)
{
this.databaseName = databaseName;
this.serverAddress = serverAddress;
this.pwd = pwd;
this.userName = userName;
connected = false;
}
public void Connect()
{
if (connected == true)
{
Console.Write("There is already a connection");
}
else
{
connected = false;
String connectionString = "server=" + serverAddress + ";" + "database=" + databaseName + ";" + "uid=" + userName + ";" + "pwd=" + pwd + ";";
Console.WriteLine(connectionString);
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(connectionString);
conn.Open();
Console.Write("Connection was succesfull");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
}
public Boolean IsConnected()
{
return connected;
}
public MySql.Data.MySqlClient.MySqlConnection getConnection()
{
return conn;
}
public void Close()
{
conn.Close();
connected = false;
}
}
然后我像这样检索数据:
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace daily_CC_SP_update
{
class Program
{
static void Main()
{
DbConnection mySQLConn = new DbConnection(dbName, serverAddress, pwd, userName);
mySQLConn.Connect();
string sqlQuery = "SELECT * FROM tbl_CC_SP";
MySqlCommand sqlCom = new MySqlCommand(sqlQuery, mySQLConn.getConnection());
MySqlDataReader reader = sqlCom.ExecuteReader();
Console.WriteLine("Following output from DB");
if(reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
//Keep the console alive until enter is pressed, for debugging
Console.Read();
mySQLConn.Close();
}
}
}
我将在数据库中创建一个视图来检索正确的数据。
首先澄清一下 :).. 您正在使用 SharePoint on-prem 对吗?所以我们可以使用 Farm 解决方案。
如果是,那么我会用休闲解决方案解决这个问题。
我会开发一个 SPJob(SharePoint 计时器作业)。它可能只包含在 Farm 解决方案中。基本上它看起来像这样:
- 在解决方案中创建 Farm 项目
- 添加继承自 SPJobDefinition 的 class,并将您的逻辑放入您需要覆盖的 Execute 方法中(在此方法中创建标准 SQL 连接并从 [查询此 table =56=] db 然后与您的 SPList 进行比较并完成工作 :) )(也许这里一个好的方法是在某些配置站点或某处的某些 SPList 中存储此连接字符串的一些凭据......不要对其进行硬编码;))
例如
public class CustomJob : SPJobDefinition
{
public CustomJob() : base() { }
public CustomJob(string jobName, SPService service) : base(jobName, service, null, SPJobLockType.None)
{
this.Title = jobName;
}
public CustomJob(string jobName, SPWebApplication webapp) : base(jobName, webapp, null, SPJobLockType.ContentDatabase)
{
this.Title = jobName;
}
public override void Execute(Guid targetInstanceId)
{
SPWebApplication webApp = this.Parent as SPWebApplication;
try
{
// Your logic here
}
catch (Exception ex)
{
SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("CustomJob - Execute", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
}
}
}
- 向范围为 webApplication 的解决方案添加新功能,并向该功能添加事件接收器
- 在功能激活时注册您的计时器作业(记得在停用时将其删除 :))
public class Feature2EventReceiver : SPFeatureReceiver
{
const string JobName = "CustomJob";
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
// add job
SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
DeleteExistingJob(JobName, parentWebApp);
CreateJob(parentWebApp);
});
}
catch (Exception ex)
{
SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("CustomJob-FeatureActivated", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
}
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
lock (this)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
// delete job
SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
DeleteExistingJob(JobName, parentWebApp);
});
}
catch (Exception ex)
{
SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("CustomJob-FeatureDeactivating", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
}
}
}
private bool CreateJob(SPWebApplication site)
{
bool jobCreated = false;
try
{
// schedule job for once a day
CustomJob job = new CustomJob(JobName, site);
SPDailySchedule schedule = new SPDailySchedule();
schedule.BeginHour = 0;
schedule.EndHour = 1;
job.Schedule = schedule;
job.Update();
}
catch (Exception)
{
return jobCreated;
}
return jobCreated;
}
public bool DeleteExistingJob(string jobName, SPWebApplication site)
{
bool jobDeleted = false;
try
{
foreach (SPJobDefinition job in site.JobDefinitions)
{
if (job.Name == jobName)
{
job.Delete();
jobDeleted = true;
}
}
}
catch (Exception)
{
return jobDeleted;
}
return jobDeleted;
}
}
在 Web 应用程序上部署并激活您的功能(我认为最好的办法是将作业配置为 运行 每天或每小时)
** 更新 **
对于 SharePoint Online,上述解决方案将不起作用,因为它是场解决方案。在 Online 中,解决方案一如既往地 'external' :)。
如果您在线存储 SP 的解决方案(例如提供商托管的 SP 应用程序等),您肯定已经拥有某种服务器。
我的方法是开发一个简单的 C# 控制台应用程序。首先在此应用程序中执行 SQL 连接 mySql 并查询 table 以获取数据.. 然后使用 CSOM 查询 SharePoint 列表进行比较。
像这样
using (var clientContext = new ClientContext("url"))
{
CamlQuery camlQuery = new CamlQuery();
string query = "add some query here";
camlQuery.ViewXml = query;
collListItem = list.GetItems(camlQuery);
clientContext.Load(collListItem, items => items.Include( item => item["Title"], item => .... // add other columns You need here);
clientContext.ExecuteQuery();
if (collListItem.Count > 0)
{
// Your code here :)
}
}
另请注意,您可以 运行 CSOM 使用不同用户(例如某种管理员)的凭据提供网络凭据,如下所示:
NetworkCredential _myCredentials = new NetworkCredential("user", "password", "companydomain");
另请注意 CSOM 中的阈值...您始终可以使用分页查询,前提是您首先获得 5000 项,然后低于 5000 项,依此类推,直到集合为空 :)。
在您 运行 手动几次此控制台应用程序以确保其正常工作后,只需将此控制台应用程序作为任务库中的新任务添加到此服务器上的任务计划程序即可。您还可以提供触发时间,例如每小时或每天 运行 等。here 是一个很好的堆栈溢出 post 如何添加此类任务
..我希望现在的答案对您的环境更好:)
所以我的c#程序有了很大的进步。我使用 MySql.Data CSOM 在 MySql 数据库和 SharePoint Online 之间建立了功能齐全的连接。可以操作和控制里面的所有列表和数据。
但是我有一个问题,不知道是否可以解决。关于这个主题,我几乎找不到任何信息。
我创建了一个新的 ListItem。将所有字段设置为一个值。但是有一列的类型是 "Person"。每个员工都有自己的站点,可以链接到该站点,例如 Lookup。向该字段添加值时,服务器出现以下错误:
Microsoft.SharePoint.Client.ServerException: Invalid data has been used to update the list item. The field you are trying to update may be read only.
at Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream responseStream)
at Microsoft.SharePoint.Client.ClientRequest.ProcessResponse()
at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder sb)
at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()
at SPList.CreateNewItem(String userName, Int32 employeeNumber, String fullName, String firstName, String lastName, DateTime emplymentStart, DateTime employmentEnd, String department, String mobile, String address, String postcode, String postTown, String email) in C:\Users\fjs\source\repos\daily_CC_SP_update\SPList.cs:line 153
SharePoint field spec
这是我创建新项目的代码。
using System;
using Microsoft.SharePoint.Client;
using System.Linq;
using System.Net;
public class SPList
{
private readonly ClientContext context;
private readonly List list;
private readonly ListItemCollection items;
private readonly Web web;
//Credentials may be needed, its commented out!
public SPList(String siteUrl, String listName, NetworkCredential netCred)
{
try
{
//NetworkCredential _myCredentials = netCred;
context = new ClientContext(siteUrl);
list = context.Web.Lists.GetByTitle(listName);
items = list.GetItems(CamlQuery.CreateAllItemsQuery());
web = context.Web;
context.Load(items);
context.Load(list);
context.Load(context.Web.Lists, lists => lists.Include(list => list.Title));
context.ExecuteQuery();
Console.WriteLine("Connected to SharePoint successfully!");
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
public void CreateNewItem(String userName, int employeeNumber, String fullName, String firstName, String lastName, DateTime emplymentStart, DateTime employmentEnd, String department, String mobile, String address, String postcode, String postTown, String email)
{
try
{
ListItemCreationInformation newItemSepc = new ListItemCreationInformation();
ListItem newItem = list.AddItem(newItemSepc);
newItem["Title"] = userName;
newItem["Employee_x0020_Number"] = employeeNumber;
newItem["Full_x0020_Name"] = fullName;
newItem["First_x0020_Name"] = firstName;
newItem["Last_x0020_Name"] = lastName;
newItem["_x000a_Employment_x0020_start_x0"] = emplymentStart.Date;
newItem["Employment_x0020_end_x0020_date"] = employmentEnd.Date;
newItem["Department"] = department;
newItem["Mobile"] = mobile;
newItem["Adress"] = address;
newItem["Postcode"] = postcode;
newItem["Post_x0020_town"] = postTown;
newItem["Email"] = email;
newItem["Person"] = fullName;
newItem.Update();
context.ExecuteQuery();
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
}
如果我评论 newItem["Person"] = fullName;代码工作正常。 这能以某种方式解决吗?否则我必须在 SharePoint 中添加项目并添加值:/
奇怪的字段名称是因为 SharePoint 出于某种原因以这种方式存储它
解决方案是将项目["LockUpColumn"]设置为锁定字段而不是字符串
我有一个保存个人信息的 MySQL 数据库。每当雇用新员工时 he/she 填写一些个人信息,这些数据就会存储在 table.
中经过一些研究(因为我无法访问其他系统 - 只有数据库),计划是构建一个 C# 控制台应用程序来检索数据并根据 SharePoint 列表检查它。如果以前 SharePoint 列表中不存在的数据库中有新记录,我想更新列表(创建新项目)。
请注意,如果 SharePoint 列表包含更多列,则 table 包含额外的手动信息。
我已经发布了针对数据库的连接代码以及我如何检索数据。
如何检查项目是否存在于 SharePoint 列表中?有人能提供一个答案,其中包括用于创建和插入新项目的代码吗?我有两列(在数据库和 SP 列表中)可以用作主键。
有一个支持 CRUD 的 REST API,所以我想这应该是一个明智的选择。
SharePoint 列表:
using System;
using System.Windows;
public class DbConnection
{
private String databaseName;
private String serverAddress;
private String pwd;
private String userName;
private Boolean connected;
private MySql.Data.MySqlClient.MySqlConnection conn;
public DbConnection(String databaseName, String serverAddress, String pwd, String userName)
{
this.databaseName = databaseName;
this.serverAddress = serverAddress;
this.pwd = pwd;
this.userName = userName;
connected = false;
}
public void Connect()
{
if (connected == true)
{
Console.Write("There is already a connection");
}
else
{
connected = false;
String connectionString = "server=" + serverAddress + ";" + "database=" + databaseName + ";" + "uid=" + userName + ";" + "pwd=" + pwd + ";";
Console.WriteLine(connectionString);
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(connectionString);
conn.Open();
Console.Write("Connection was succesfull");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
}
public Boolean IsConnected()
{
return connected;
}
public MySql.Data.MySqlClient.MySqlConnection getConnection()
{
return conn;
}
public void Close()
{
conn.Close();
connected = false;
}
}
然后我像这样检索数据:
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace daily_CC_SP_update
{
class Program
{
static void Main()
{
DbConnection mySQLConn = new DbConnection(dbName, serverAddress, pwd, userName);
mySQLConn.Connect();
string sqlQuery = "SELECT * FROM tbl_CC_SP";
MySqlCommand sqlCom = new MySqlCommand(sqlQuery, mySQLConn.getConnection());
MySqlDataReader reader = sqlCom.ExecuteReader();
Console.WriteLine("Following output from DB");
if(reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
//Keep the console alive until enter is pressed, for debugging
Console.Read();
mySQLConn.Close();
}
}
}
我将在数据库中创建一个视图来检索正确的数据。
首先澄清一下 :).. 您正在使用 SharePoint on-prem 对吗?所以我们可以使用 Farm 解决方案。 如果是,那么我会用休闲解决方案解决这个问题。 我会开发一个 SPJob(SharePoint 计时器作业)。它可能只包含在 Farm 解决方案中。基本上它看起来像这样:
- 在解决方案中创建 Farm 项目
- 添加继承自 SPJobDefinition 的 class,并将您的逻辑放入您需要覆盖的 Execute 方法中(在此方法中创建标准 SQL 连接并从 [查询此 table =56=] db 然后与您的 SPList 进行比较并完成工作 :) )(也许这里一个好的方法是在某些配置站点或某处的某些 SPList 中存储此连接字符串的一些凭据......不要对其进行硬编码;)) 例如
public class CustomJob : SPJobDefinition
{
public CustomJob() : base() { }
public CustomJob(string jobName, SPService service) : base(jobName, service, null, SPJobLockType.None)
{
this.Title = jobName;
}
public CustomJob(string jobName, SPWebApplication webapp) : base(jobName, webapp, null, SPJobLockType.ContentDatabase)
{
this.Title = jobName;
}
public override void Execute(Guid targetInstanceId)
{
SPWebApplication webApp = this.Parent as SPWebApplication;
try
{
// Your logic here
}
catch (Exception ex)
{
SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("CustomJob - Execute", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
}
}
}
- 向范围为 webApplication 的解决方案添加新功能,并向该功能添加事件接收器
- 在功能激活时注册您的计时器作业(记得在停用时将其删除 :))
public class Feature2EventReceiver : SPFeatureReceiver
{
const string JobName = "CustomJob";
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
// add job
SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
DeleteExistingJob(JobName, parentWebApp);
CreateJob(parentWebApp);
});
}
catch (Exception ex)
{
SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("CustomJob-FeatureActivated", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
}
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
lock (this)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate ()
{
// delete job
SPWebApplication parentWebApp = (SPWebApplication)properties.Feature.Parent;
DeleteExistingJob(JobName, parentWebApp);
});
}
catch (Exception ex)
{
SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("CustomJob-FeatureDeactivating", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
}
}
}
private bool CreateJob(SPWebApplication site)
{
bool jobCreated = false;
try
{
// schedule job for once a day
CustomJob job = new CustomJob(JobName, site);
SPDailySchedule schedule = new SPDailySchedule();
schedule.BeginHour = 0;
schedule.EndHour = 1;
job.Schedule = schedule;
job.Update();
}
catch (Exception)
{
return jobCreated;
}
return jobCreated;
}
public bool DeleteExistingJob(string jobName, SPWebApplication site)
{
bool jobDeleted = false;
try
{
foreach (SPJobDefinition job in site.JobDefinitions)
{
if (job.Name == jobName)
{
job.Delete();
jobDeleted = true;
}
}
}
catch (Exception)
{
return jobDeleted;
}
return jobDeleted;
}
}
在 Web 应用程序上部署并激活您的功能(我认为最好的办法是将作业配置为 运行 每天或每小时)
** 更新 **
对于 SharePoint Online,上述解决方案将不起作用,因为它是场解决方案。在 Online 中,解决方案一如既往地 'external' :)。 如果您在线存储 SP 的解决方案(例如提供商托管的 SP 应用程序等),您肯定已经拥有某种服务器。 我的方法是开发一个简单的 C# 控制台应用程序。首先在此应用程序中执行 SQL 连接 mySql 并查询 table 以获取数据.. 然后使用 CSOM 查询 SharePoint 列表进行比较。 像这样
using (var clientContext = new ClientContext("url"))
{
CamlQuery camlQuery = new CamlQuery();
string query = "add some query here";
camlQuery.ViewXml = query;
collListItem = list.GetItems(camlQuery);
clientContext.Load(collListItem, items => items.Include( item => item["Title"], item => .... // add other columns You need here);
clientContext.ExecuteQuery();
if (collListItem.Count > 0)
{
// Your code here :)
}
}
另请注意,您可以 运行 CSOM 使用不同用户(例如某种管理员)的凭据提供网络凭据,如下所示:
NetworkCredential _myCredentials = new NetworkCredential("user", "password", "companydomain");
另请注意 CSOM 中的阈值...您始终可以使用分页查询,前提是您首先获得 5000 项,然后低于 5000 项,依此类推,直到集合为空 :)。 在您 运行 手动几次此控制台应用程序以确保其正常工作后,只需将此控制台应用程序作为任务库中的新任务添加到此服务器上的任务计划程序即可。您还可以提供触发时间,例如每小时或每天 运行 等。here 是一个很好的堆栈溢出 post 如何添加此类任务
..我希望现在的答案对您的环境更好:)
所以我的c#程序有了很大的进步。我使用 MySql.Data CSOM 在 MySql 数据库和 SharePoint Online 之间建立了功能齐全的连接。可以操作和控制里面的所有列表和数据。
但是我有一个问题,不知道是否可以解决。关于这个主题,我几乎找不到任何信息。
我创建了一个新的 ListItem。将所有字段设置为一个值。但是有一列的类型是 "Person"。每个员工都有自己的站点,可以链接到该站点,例如 Lookup。向该字段添加值时,服务器出现以下错误:
Microsoft.SharePoint.Client.ServerException: Invalid data has been used to update the list item. The field you are trying to update may be read only.
at Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream responseStream)
at Microsoft.SharePoint.Client.ClientRequest.ProcessResponse()
at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder sb)
at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()
at SPList.CreateNewItem(String userName, Int32 employeeNumber, String fullName, String firstName, String lastName, DateTime emplymentStart, DateTime employmentEnd, String department, String mobile, String address, String postcode, String postTown, String email) in C:\Users\fjs\source\repos\daily_CC_SP_update\SPList.cs:line 153
SharePoint field spec
这是我创建新项目的代码。
using System;
using Microsoft.SharePoint.Client;
using System.Linq;
using System.Net;
public class SPList
{
private readonly ClientContext context;
private readonly List list;
private readonly ListItemCollection items;
private readonly Web web;
//Credentials may be needed, its commented out!
public SPList(String siteUrl, String listName, NetworkCredential netCred)
{
try
{
//NetworkCredential _myCredentials = netCred;
context = new ClientContext(siteUrl);
list = context.Web.Lists.GetByTitle(listName);
items = list.GetItems(CamlQuery.CreateAllItemsQuery());
web = context.Web;
context.Load(items);
context.Load(list);
context.Load(context.Web.Lists, lists => lists.Include(list => list.Title));
context.ExecuteQuery();
Console.WriteLine("Connected to SharePoint successfully!");
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
public void CreateNewItem(String userName, int employeeNumber, String fullName, String firstName, String lastName, DateTime emplymentStart, DateTime employmentEnd, String department, String mobile, String address, String postcode, String postTown, String email)
{
try
{
ListItemCreationInformation newItemSepc = new ListItemCreationInformation();
ListItem newItem = list.AddItem(newItemSepc);
newItem["Title"] = userName;
newItem["Employee_x0020_Number"] = employeeNumber;
newItem["Full_x0020_Name"] = fullName;
newItem["First_x0020_Name"] = firstName;
newItem["Last_x0020_Name"] = lastName;
newItem["_x000a_Employment_x0020_start_x0"] = emplymentStart.Date;
newItem["Employment_x0020_end_x0020_date"] = employmentEnd.Date;
newItem["Department"] = department;
newItem["Mobile"] = mobile;
newItem["Adress"] = address;
newItem["Postcode"] = postcode;
newItem["Post_x0020_town"] = postTown;
newItem["Email"] = email;
newItem["Person"] = fullName;
newItem.Update();
context.ExecuteQuery();
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
}
如果我评论 newItem["Person"] = fullName;代码工作正常。 这能以某种方式解决吗?否则我必须在 SharePoint 中添加项目并添加值:/
奇怪的字段名称是因为 SharePoint 出于某种原因以这种方式存储它
解决方案是将项目["LockUpColumn"]设置为锁定字段而不是字符串