Создание новой задачи с ExchangeService в Office 365 - PullRequest
2 голосов
/ 28 апреля 2019

Все старые ExchangeService примеры выглядят великолепно:

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"

Первая часть исключения, вероятно, из словаря,часть "Key ..." неизвестна.

Источник исключения: "System.Private.CoreLib" .

Какая правильная реализация для создания новой задачив Exchange / Office 365 Online?

1 Ответ

1 голос
/ 30 апреля 2019

Как говорит @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);

TaskManager:

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

        }
    }
}
...