c# - 在 Office 365 上使用 ExchangeService 创建新任务

标签 c# .net-core office365 exchangewebservices

所有的旧ExchangeService examples看起来很棒:

exchangeService = new ExchangeService();
exchangeServie.Credentials = new WebCredentials('user', 'pass');
exchangeService.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
var task = new Task(exchangeService);
task.Subject = "...";
task.Body = "..";
task.Save(WellKnownFolderName.Tasks);

但它不适用于 Office 365,它会抛出异常:

"An item with the same key has already been added. Key: Std/1916"

异常的第一部分可能来自字典,“Key...”部分未知。

异常的来源是“System.Private.CoreLib”

在 Exchange/Office 365 Online 中创建新任务的正确实现是什么?

最佳答案

正如@Nkosi 所说,我不确定错误是否可以追溯到您提供的示例。不过,我可以回答以下问题:在 Exchange/Office 365 Online 中创建新任务的正确实现是什么?

我会查看示例:Office 365:在 Exchange Online 中创建任务

https://code.msdn.microsoft.com/office/SharePoint-Online-Set-up-a-d5207541/view/SourceCode#content

查看方法 CreateTask(string subject, string message,DateTime startDate)。我认为它与您的示例非常相似,但我不知道您的 ExchangeService 是如何设置的。我会尝试让代码与下面的代码一起使用,然后在您的解决方案中实现它。

模型:

/// <summary>
/// Task creator credentials.
/// </summary>
public class UserModel
{
    public string TaskCreatorEmailID { get; set; }
    public string Password { get; set; }

}

/// <summary>
/// Task entity along with attributes.
/// </summary>
public class TaskModel
{
    public string TaskTitle { get; set; }
    public string TaskMessage { get; set; }
    public DateTime TaskStartDate { get; set; }
}

/// <summary>
/// User's task collection along with user information.
/// </summary>
public class UserTasksModel
{
    public UserModel User { get; set; }
    public TaskModel NewTask { get; set; }
    public List<TaskModel> Tasks { get; set; }
}

调用方法:

//Create TaskManager instance with user credentials.
TaskManager taskManager = new TaskManager(model.User.TaskCreatorEmailID, model.User.Password);

//Call create task method
taskManager.CreateTask(model.NewTask.TaskTitle, model.NewTask.TaskMessage, model.NewTask.TaskStartDate);

任务管理器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using Microsoft.Exchange.WebServices.Data;

namespace ManagingTasksUsingEWS
{
    public class TaskManager
    {
        private  ExchangeService _service;
        private  string _taskCreatorEmailID;
        private  string _password;
        public ExchangeService Service;


        public TaskManager(string taskCreatorEmailID,string password)
        {
            _taskCreatorEmailID = taskCreatorEmailID;
            _password = password;
            Service = GetExchangeService();
        }

        private ExchangeService GetExchangeService()
        {
            if (_service == null)
            {
                ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
                _service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
                _service.Credentials = new WebCredentials(_taskCreatorEmailID, _password);
                _service.TraceEnabled = true;
                _service.TraceFlags = TraceFlags.All;
                _service.AutodiscoverUrl(_taskCreatorEmailID, RedirectionUrlValidationCallback);
            }
            return _service;
        }

        private static bool CertificateValidationCallBack(
                            object sender,
                            System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                            System.Security.Cryptography.X509Certificates.X509Chain chain,
                            System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            // If the certificate is a valid, signed certificate, return true.
            if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
            {
                return true;
            }

            // If there are errors in the certificate chain, look at each error to determine the cause.
            if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
            {
                if (chain != null && chain.ChainStatus != null)
                {
                    foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
                    {
                        if ((certificate.Subject == certificate.Issuer) &&
                           (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
                        {
                            // Self-signed certificates with an untrusted root are valid. 
                            continue;
                        }
                        else
                        {
                            if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
                            {
                                // If there are any other errors in the certificate chain, the certificate is invalid,
                                // so the method returns false.
                                return false;
                            }
                        }
                    }
                }

                // When processing reaches this line, the only errors in the certificate chain are 
                // untrusted root errors for self-signed certificates. These certificates are valid
                // for default Exchange server installations, so return true.
                return true;
            }
            else
            {
                // In all other cases, return false.
                return false;
            }
        }

        private static bool RedirectionUrlValidationCallback(string redirectionUrl)
        {
            // The default for the validation callback is to reject the URL.
            bool result = false;

            Uri redirectionUri = new Uri(redirectionUrl);

            // Validate the contents of the redirection URL. In this simple validation
            // callback, the redirection URL is considered valid if it is using HTTPS
            // to encrypt the authentication credentials. 
            if (redirectionUri.Scheme == "https")
            {
                result = true;
            }
            return result;
        }

        /// <summary>
        /// The method will create task in "Tasks" folder
        /// </summary>
        /// <param name="subject">Subject of the task</param>
        /// <param name="message">Message body of the task</param>
        /// <param name="startDate">Start date of the task</param>
        /// 
        public  void CreateTask(string subject, string message,DateTime startDate)
        {
            // Instaniate the Task object.
            Task task = new Task(Service);

            // Assign the subject, body and start date of the new task.
            task.Subject = subject;
            task.Body = new MessageBody(BodyType.Text,message);
            task.StartDate = startDate;

            // Create the new task in the Tasks folder.
            task.Save(WellKnownFolderName.Tasks);

        }
    }
}

关于c# - 在 Office 365 上使用 ExchangeService 创建新任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55889734/

相关文章:

C# - 代码契约(Contract) - 检测到的表达式语句评估潜在的副作用

c# - 反序列化 xmlarray 的 xml 属性

.net-core - 无法在基于 alpine 的 dotnet SDK 中运行 gRPC 协议(protocol)

c# - gRPC 相当于 WCF 服务发现

azure - 域名扩展需要 localhost (127.0.0.1)

c# - 以编程方式向文件夹添加权限

c# - 想在 asp.net 中使用 c++ 库和 dll

c# - 在 C# 类中找不到默认接口(interface)

vba - VBA 中未定义文档类型

sandbox - 在 Sharepoint office 365 中激活沙盒解决方案