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

C# 在Office 365上使用ExchangeService创建新任务,c#,.net-core,office365,exchangewebservices,C#,.net Core,Office365,Exchangewebservices,所有的老人看起来都很棒: 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.Subjec

所有的老人看起来都很棒:

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,它引发异常:

“已添加具有相同密钥的项。密钥:Std/1916”

例外情况的第一部分可能来自字典,“键…”部分未知

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


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

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

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

查看方法
CreateTask(字符串主题、字符串消息、日期时间开始日期)
。我认为这与您的示例非常相似,但我不知道您的
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; }
}
任务经理:

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);

        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
Net系统;
使用System.Web;
使用Microsoft.Exchange.WebServices.Data;
命名空间管理任务使用News
{
公共类任务管理器
{
私人交换服务;
私有字符串_taskCreatorEmailID;
私有字符串\u密码;
公共交换服务;
公共任务管理器(字符串taskCreatorEmailID,字符串密码)
{
_taskCreatorEmailID=taskCreatorEmailID;
_密码=密码;
服务=GetExchangeService();
}
私有ExchangeService GetExchangeService()
{
if(_service==null)
{
ServicePointManager.ServerCertificateValidationCallback=CertificateValidationCallBack;
_服务=新的ExchangeService(ExchangeVersion.Exchange2010_SP2);
_service.Credentials=新的WebCredentials(_taskCreatorEmailID,_密码);
_service.TraceEnabled=true;
_service.TraceFlags=TraceFlags.All;
_自动发现URL(_taskCreatorEmailID,RedirectionUrlValidationCallback);
}
退货服务;
}
私有静态bool CertificateValidationCallBack(
对象发送器,
System.Security.Cryptography.X509Certificates.X509Certificate证书,
System.Security.Cryptography.X509Certificates.X509Chain-chain,
System.Net.Security.SslPolicyErrors SslPolicyErrors)
{
//如果证书是有效的签名证书,则返回true。
if(sslPolicyErrors==System.Net.Security.sslPolicyErrors.None)
{
返回true;
}
//如果证书链中存在错误,请查看每个错误以确定原因。
if((sslPolicyErrors&System.Net.Security.sslPolicyErrors.RemoteCertificateChaineErrors)!=0)
{
if(chain!=null&&chain.ChainStatus!=null)
{
foreach(System.Security.Cryptography.X509Certificates.X509ChainStatus在chain.ChainStatus中的状态)
{
if((certificate.Subject==certificate.Issuer)&&
(status.status==System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.untrustroot))
{
//具有不受信任根的自签名证书有效。
继续;
}
其他的
{
if(status.status!=System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
{
//如果证书链中存在任何其他错误,则证书无效,
//因此,该方法返回false。
返回false;
}
}
}
}
//当处理到达此行时,证书链中唯一的错误是
//自签名证书的不受信任根错误。这些证书有效
//对于默认的Exchange server安装,请返回true。
返回true;
}
其他的
{
//在所有其他情况下,返回false。
返回false;
}
}
私有静态bool重定向UrlValidationCallback(字符串重定向Url)
{
//验证回调的默认值是拒绝URL。
布尔结果=假;
Uri redirectionUri=新Uri(redirectionUrl);
//验证重定向URL的内容
//如果使用HTTPS,则重定向URL被视为有效
//加密身份验证凭据。
if(redirectionUri.Scheme==“https”)
{
结果=真;
}
返回结果;
}
/// 
///该方法将在“任务”文件夹中创建任务
/// 
///任务主题
///任务的消息体
///任务的开始日期
/// 
public void CreateTask(字符串主题、字符串消息、日期时间开始日期)
{
//实例化任务对象。
任务=新任务(服务);
//指定新任务的主题、正文和开始日期。
task.Subject=Subject;
task.Body=newmessagebody(
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);

        }
    }
}