簡體   English   中英

EWS托管API如何測試C#應用程序

[英]EWS managed API how to test the C# Application

我正在嘗試創建一個將在后台連續運行的進程。 該服務將查看收件箱中收到的新電子郵件,並解析電子郵件。 我們有Exchange Server,所以我正在使用Exchange托管API。 我已經創建了EWS文檔中提到的C#類。 我有單獨測試的服務實例。 我正在收件箱上創建流式通知和新郵件事件。 但是我不知道如何測試應用程序,因為我關閉了應用程序控制台窗口,然后手動將郵件發送到收件箱,但是不知道何時會觸發新郵件事件以及是否會在控制台上顯示消息。 我不確定是否需要在服務器端提供某些東西或對其進行配置。 我想知道是否有任何方法可以保持此進程在不使用30分鍾的情況下運行。 我想創建服務的時間間隔。 請尋求幫助。

          namespace NewMailNotification
          {
            class Program
                {
                   static void Main(string[] args)
                      {
                       ExchangeService service = new ExchangeService  (ExchangeVersion.Exchange2010_SP2);

            service.Url = null;
            string user = ConfigurationSettings.AppSettings["user"];
           string userid = ConfigurationSettings.AppSettings["user-id"];
            string PWD = ConfigurationSettings.AppSettings["PWD"];

            try
            {
                service.Credentials = new WebCredentials(user.ToString(), PWD.ToString());
                service.AutodiscoverUrl(userid.ToString(), RedirectionUrlValidationCallback);
            }
            catch (Exception e)
            {
                Console.WriteLine("---" + e.Message);
            }

            SetStreamingNotification(service);

    }
    private static bool RedirectionUrlValidationCallback(string RedirectionUrl)
    {
        bool result = false;

        Uri redirectionUri = new Uri(RedirectionUrl);

        if (redirectionUri.Scheme == "https")
        {
            Console.WriteLine(redirectionUri);
            result = true;
        }
        return result;

    }
    //Notification subscription and event
    static void SetStreamingNotification(ExchangeService service)
    {
        //subscribe to streaming notification onthe inbox folder, and listen to newmail
        StreamingSubscription streamingsubscription = service.SubscribeToStreamingNotifications(new FolderId[] { WellKnownFolderName.Inbox },
            EventType.NewMail,
            EventType.Created, 
            EventType.Deleted);

        StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(service, 30);

        connection.AddSubscription(streamingsubscription);

        //Delegate an event handlers
        connection.OnNotificationEvent += 
            new StreamingSubscriptionConnection.NotificationEventDelegate(OnEvent);
        connection.OnSubscriptionError +=
            new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnError);
        connection.OnDisconnect +=
            new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnDisconnect);
        connection.Open();

        Console.WriteLine("--------- StreamSubscription event -------");
    }



    static void OnEvent(object sender, NotificationEventArgs args)
    {
        StreamingSubscription subscription = args.Subscription;
        //Loop through all item-related events.
        foreach(NotificationEvent notification in args.Events)
        {
            switch (notification.EventType)
            {
                case EventType.NewMail:
                    Console.WriteLine("\n----------------Mail Received-----");
                    break;
                case EventType.Created:
                    Console.WriteLine("\n-------------Item or Folder deleted-------");
                    break;
                case EventType.Deleted:
                    Console.WriteLine("\n------------Item or folder deleted---------");
                    break;
            }
            //Display the notification identifier.
            if (notification is ItemEvent)
            {
                //The notificationEvent for a folder is a Folderevent.
                FolderEvent folderevent = (FolderEvent)notification;
                Console.WriteLine("\nFolderId: " + folderevent.FolderId.UniqueId);
            }
            else
            {
                //The notificationevent for a foler is a FolderEvent
                FolderEvent folderevent = (FolderEvent)notification;
                Console.WriteLine("\nFolderId: " + folderevent.FolderId.UniqueId);

            }
        }
    }


    static private void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
    {
        StreamingSubscriptionConnection connection = (StreamingSubscriptionConnection)sender;
        //ask the usr if they want to reconnect or close the connection
        ConsoleKeyInfo cki;
        Console.WriteLine("The connection to the subscription is disconnected.");
        Console.WriteLine("Do you want to reconnect to the subscription? Y/N");
        while (true)
        {
            cki = Console.ReadKey(true);
            {
                if (cki.Key == ConsoleKey.Y)
                {
                    connection.Open();
                    Console.WriteLine("Connection Open.");
                    Console.WriteLine("\r\n");
                    break;
                }
                else if (cki.Key == ConsoleKey.N)
                {
                    // Signal.Set();
                    bool isOpen = connection.IsOpen;

                    if (isOpen == true)
                    {
                        connection.Close();
                    }
                    else
                    {
                        break;
                    }

                }
            }//while end
        }
    }

      static void OnError(object sender,SubscriptionErrorEventArgs args)
      {
          Exception e=args.Exception;
          Console.WriteLine("\n------------Error----"+e.Message+"----------");
      }
  }//class end

} //命名空間結尾

您好,我已經完成了創建控制台應用程序的操作,並且沒有關閉控制台應用程序。

我寫的最后一行是“ Console.ReadLine()”

當您收到新電子郵件時,將觸發OnNotificationEvent事件。

下面是示例代碼。

class Program
    {
        static void Main(string[] args)
        {
            EmailExchange emailExchange = new EmailExchange();
            emailExchange.Domain = ConfigurationManager.AppSettings["Domain"];
            emailExchange.EmailID = ConfigurationManager.AppSettings["EmailID"];
            emailExchange.Password = ConfigurationManager.AppSettings["Password"];                
            emailExchange.Watch();

            Console.ReadLine();
        }

    }


public class EmailExchange : IDisposable
    {
        public string Password { get; set; }
        public string EmailID { get; set; }
        public string Domain { get; set; }            
        public string ExchangeURL
        {
            get { return "https://outlook.office365.com/EWS/Exchange.asmx"; }
        }        
        private StreamingSubscriptionConnection connection = null;
        private ExchangeService service = null;
        public void Watch()
        {
            service = new ExchangeService();
            service.Credentials = new WebCredentials(EmailID, Password, Domain);            
            service.Url = new Uri(ExchangeURL);
            StreamingSubscription streamingsubscription = service.SubscribeToStreamingNotifications(new FolderId[] { WellKnownFolderName.Inbox }, EventType.NewMail);            
            connection = new StreamingSubscriptionConnection(service, 5);
            connection.AddSubscription(streamingsubscription);
            connection.OnNotificationEvent += OnNotificationEvent;
            connection.OnSubscriptionError += OnSubscriptionError;
            connection.OnDisconnect += OnDisconnect;
            connection.Open();
        }

        private void OnDisconnect(object sender, SubscriptionErrorEventArgs args)
        {
            Console.WriteLine("Disconnected");
            if (!connection.IsOpen)
                connection.Open();
        }

        private void OnSubscriptionError(object sender, SubscriptionErrorEventArgs args)
        {

        }

        private void OnNotificationEvent(object sender, NotificationEventArgs args)
        {
            foreach (var notification in args.Events)
            {
                if (notification.EventType != EventType.NewMail) continue;

                var itemEvent = (ItemEvent)notification;               
                // add you code here
            }
        }



        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }
    }

這是使其運行的代碼。 我可以查看傳入的電子郵件中的30薄荷糖。 盡管先前的代碼將與帶有一個郵箱的帳戶一起運行。 但是,如果您有兩個以上的郵箱,那么我們必須指定我們需要監視的郵箱。

     static void Main(string[] args)
    {
        ExchangeService service = new ExchangeService  (ExchangeVersion.Exchange2010_SP2);
        //***********New**********************
        ExchangeService  mailbox = new ExchangeService(ExchangeVersion.Exchange2010_SP2); 
        string mailboxEmail = ConfigurationSettings.AppSettings["user-id"]; 
        WebCredentials wbcred = new WebCredentials(ConfigurationSettings.AppSettings["user"], ConfigurationSettings.AppSettings["PWD"]); 
        mailbox.Credentials = wbcred;
    //    mailbox.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, mailboxEmail);

          mailbox.AutodiscoverUrl(mailboxEmail,  RedirectionUrlValidationCallback);
        mailbox.HttpHeaders.Add("X-AnchorMailBox", mailboxEmail);
        FolderId mb1Inbox = new FolderId(WellKnownFolderName.Inbox, mailboxEmail);
         SetStreamingNotification(mailbox, mb1Inbox);
         bool run = true;
        while (run)
        {
            System.Threading.Thread.Sleep(100);
        }
    }

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

        Uri redirectionUri=new Uri(redirectionUrl);
        if(redirectionUri.Scheme=="https")
        {
            result=true;
        }
        return result;
    }

    static void SetStreamingNotification(ExchangeService service,FolderId fldId)
    {
        StreamingSubscription streamingssubscription=service.SubscribeToStreamingNotifications(new FolderId[]{fldId},
            EventType.NewMail,
            EventType.Created,
            EventType.Deleted);

        StreamingSubscriptionConnection connection=new StreamingSubscriptionConnection(service,30);
        connection.AddSubscription(streamingssubscription);

        //Delagate event handlers
        connection.OnNotificationEvent+=new StreamingSubscriptionConnection.NotificationEventDelegate(OnEvent);
        connection.OnSubscriptionError+=new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnError);
        connection.Open();

    }

    static void OnEvent(object sender,NotificationEventArgs args)
    {
        StreamingSubscription subscription=args.Subscription;
        if(subscription.Service.HttpHeaders.ContainsKey("X-AnchorMailBox"))
        {
            Console.WriteLine("event for nailbox"+subscription.Service.HttpHeaders["X-AnchorMailBox"]);
        }
        //loop through all the item-related events.
        foreach(NotificationEvent notification in args.Events)
        {
            switch(notification.EventType)
            {
                case EventType.NewMail:
                    Console.WriteLine("\n----------------Mail Received-----");
                    break;
                case EventType.Created:
                    Console.WriteLine("\n-------------Item or Folder deleted-------");
                    break;
                case EventType.Deleted:
                    Console.WriteLine("\n------------Item or folder deleted---------");
                    break;

            }

            //Display notification identifier
            if(notification is ItemEvent)
            {
                //The NotificationEvent for an email message is an ItemEvent
                ItemEvent itemEvent=(ItemEvent)notification;
                Console.WriteLine("\nItemId:"+ itemEvent.ItemId.UniqueId);
                Item NewItem=Item.Bind(subscription.Service,itemEvent.ItemId);
                if(NewItem is EmailMessage)
                {
                    Console.WriteLine(NewItem.Subject);
                }

            }
            else
            {
                //the Notification for a Folder is an FolderEvent
                FolderEvent folderEvent=(FolderEvent)notification;
                Console.WriteLine("\nFolderId:"+folderEvent.FolderId.UniqueId);
            }
        }
    }
    static void OnError(object sender,SubscriptionErrorEventArgs args)
    {
        //Handle error conditions.
        Exception e=args.Exception;
        Console.WriteLine("\n-----Error-----"+e.Message+"--------");
    }
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM