【问题标题】:EWS managed API how to test the C# ApplicationEWS 托管 API 如何测试 C# 应用程序
【发布时间】:2015-01-23 18:23:12
【问题描述】:

我正在尝试创建一个将在后台连续运行的进程。此服务将查看收件箱中传入的新电子邮件并解析电子邮件。我们有 Exchange Server,所以我使用的是 Exchange Managed 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

}//命名空间结束

【问题讨论】:

    标签: c# .net email exchangewebservices exchange-server-2010


    【解决方案1】:

    您好,我已经创建了控制台应用程序,但我没有关闭控制台应用程序。

    我写的最后一行是“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);
            }
        }
    

    【讨论】:

      【解决方案2】:

      这是使它运行的代码。我可以观看收到的电子邮件 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+"--------");
          }
      }
      

      }

      【讨论】:

        猜你喜欢
        • 2013-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多