【问题标题】:How to update a SharePoint Online list if a new record is inserted in the database?如果在数据库中插入新记录,如何更新 SharePoint Online 列表?
【发布时间】:2019-11-02 04:48:57
【问题描述】:

我有一个保存个人信息的 MySQL 数据库。每当新员工被录用时,他/她都会填写一些个人信息,然后这些数据就会存储在表格中。

经过一些研究(并且由于我无法访问其他系统 - 只有数据库),计划是构建一个 C# 控制台应用程序来检索数据并根据 SharePoint 列表进行检查。如果数据库中有一条新记录在以前的 SharePoint 列表中不存在,我想更新列表(创建一个新项目)。

请注意,如果 SharePoint 列表包含更多列,则该表包含额外的手动信息。

我已经发布了针对数据库的连接代码以及我如何检索数据。

如何检查项目是否存在于 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();

        }
    }
}

我将在数据库中创建一个视图来检索正确的数据。

【问题讨论】:

    标签: c# mysql rest sharepoint-online sharepoint-designer


    【解决方案1】:

    首先要澄清 :).. 您使用的是本地 SharePoint 对吗?所以我们可以使用农场解决方案。 如果是,那么我将使用休闲解决方案来解决此问题。 我会开发一个 SPJob(SharePoint Timer 作业)。它可能只包含在农场解决方案中。基本上是这样的:

    1. 在解决方案中创建农场项目
    2. 添加从 SPJobDefinition 继承的类并将您的逻辑放入您需要覆盖的 Execute 方法中(在此方法中创建标准 SQL 连接并从 mySQL 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);
            }
        }
    }
    
    1. 为范围为 webApplication 的解决方案添加新功能,并向该功能添加事件接收器
    2. 在功能激活时注册您的计时器作业(记得在停用时将其删除:))
    
    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;
        }
    }
    
    1. 在网络应用程序上部署并激活您的功能(我认为最好将作业配置为每天或每小时运行)

      • 一篇不错的文章,其中包含一些如何做到这一点的示例,所有这些都可以在 here 找到(我知道这篇文章适用于 SP 2010,但它在 2013、2016 和 2019 年也适用(使用这个本地版本)我没有太多经验):)
      • 另一篇具有相同解决方案的文章 here(此为 SP 2013)

    ** 更新**

    对于 SharePoint Online,上述解决方案将不起作用,因为它是场解决方案。在 Online 中,解决方案始终是“外部”的 :)。 可以肯定的是,如果您在线存储 SP 的解决方案(例如提供商托管的 SP 应用程序等),您已经拥有某种服务器。 我的方法是开发一个简单的 C# 控制台应用程序。首先在这个应用程序中与 mySql 建立 SQL 连接并查询表以获取数据。然后使用 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 是一个很好的堆栈溢出帖子如何添加这种任务

    .. 我希望现在的答案更适合您的环境:)

    【讨论】:

    • 我没有在本地使用 SP,但在 Online 上使用,因此无法实施农场解决方案。但你最后的建议与我之前计划的一致,所以这就是要走的路。
    • ...抱歉...我从帖子中确定它是本地的...请查看我对在线方法帖子的更新
    • 没问题,谢谢更新!我会对此进行调查并提出我的解决方案!
    【解决方案2】:

    所以我的 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 出于某种原因以这种方式存储它

    【讨论】:

      【解决方案3】:

      解决方法是设置 items["LockUpColumn"] 不是字符串而是锁定字段

      【讨论】:

        猜你喜欢
        • 2015-08-14
        • 1970-01-01
        • 1970-01-01
        • 2019-06-23
        • 1970-01-01
        • 2016-01-13
        • 2019-04-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多