Thursday, July 31, 2014

'Autodiscover service couldn't be located' error while calling exchange server

The code below had been working
           
    
           ExchangeService service = new ExchangeService();
            //Assign the URL. It is recommended to use AutoDiscoverUrl but we didn’t have it configured
            string exSvcUrl = "https://exchange_server_ip_or_name/ews/exchange.asmx";
            service.Url = new Uri(exSvcUrl);

            //Set service credentials. In this case a user account who has permissions to user mailboxes.
            string domain = "xxx";
            string credUser = "mxxx";
            string credPwd = "xxxxxx";
            service.Credentials = new System.Net.NetworkCredential(credUser, credPwd, domain);
            service.AutodiscoverUrl("xxx@xxxx.com");
            try
            {
                
                SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, DateTime.Now.AddHours(-12)), new SearchFilter.ContainsSubstring(EmailMessageSchema.Sender, "xxx"));

                ItemView view = new ItemView(20);

                FindItemsResults findResults = service.FindItems(
                new FolderId(WellKnownFolderName.Inbox, new Mailbox("xxxx@xxxx.com")),
                sf,
                new ItemView(200));
            }
            catch{...}
It worked for a while, then one day after office moved, it came out the error as below:
Autodiscover service couldn't be located

It took me a while to figure this out, googled to no avail. Here is version after fix:

                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);


                //Assign the URL. It is recommended to use AutoDiscoverUrl but we didn’t have it configured
                service.Url = new Uri(exSvcUrl);

                //Set service credentials. In this case a user account who has permissions to user mailboxes.
                service.Credentials = new WebCredentials(credUser, CryptoUtility.Decrypt(credPwd, ParamForCrypto, SaltForCrypto), domain);

                if (debugMode) service.TraceEnabled = true;

                System.Net.WebProxy proxy = new System.Net.WebProxy("https://xxxx.com");
                proxy.UseDefaultCredentials = true;                

                //The search filter to get unread email

                SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, DateTime.Now.AddDays(daysToRetrieve*-1)), new SearchFilter.ContainsSubstring(EmailMessageSchema.Sender, mailbox_to_monitor));
               
                FindItemsResults findResults = service.FindItems(
                new FolderId(WellKnownFolderName.Inbox, new Mailbox(mailbox)),
                sf,
                new ItemView(200));

No comments:

Post a Comment