Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
Home
Discussion GroupsWindows Server 2003Windows 2000Windows NTSmall Business ServerVirtual ServerExchange ServerIISHost Integration ServerISA ServerSMSWSUSMOMWindows Media ServerSecurityCertification
Related Topics
SQL ServerMS WindowsMS OfficePC HardwareMore Topics ...

Windows Server Forum / Exchange Server / Applications / May 2006

Tip: Looking for answers? Try searching our database.

NotificationSampleWebDav-Monitor OWA Inbox

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
VJ - 08 May 2006 16:26 GMT
Hi,

I'm using the NotificationSampleWebDAV provided with Exchange SDK to moniter
the MailBox over the excange server and process the inbox messages when ever
new mail comes.Here I'm using the Subscribe and Poll methods of
WebDavAccessor. I'm using the application as it is, but the problem is that
when I run the application continuoulsy for more then 20 min,  I'm getting
the following error

Warning: Exiting Action with an exception: The remote server returned an
error: (440) Login Timeout.
Stack Trace for the excetion:    at
System.Net.HttpWebRequest.CheckFinalStatus()
  at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
  at System.Net.HttpWebRequest.GetResponse()

After through investigation i found that the server is creating the
SessionId and the session is expiring after 20 minutes.

I want to have the continues access to the exchange server.

Can any body help me to resolve this issue.

The code that I'm using is as follows,

static private string Action(string Uri, string Method, string
NotificationType, string SubscriptionID)
        {
           // Declare variables.
            string XmlData = "";  
            Request = null;
            byte[] bytes = null;
           WebResponse requestResponse = null;
            string Body = "";
            NetworkCredential mycred = new
System.Net.NetworkCredential(Username,Password,Domain);
           
            try
            {   
                //accept ssl certificate
                ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();

                //do form-based authentication
                if (AuthCookies==null)
                {
                    AuthCookies = DoFormbasedAuthentication(Uri, mycred);
                }

           
                // Create a new credentials cache.
                System.Net.CredentialCache MyCredentialCache = new
System.Net.CredentialCache();

                // Add user name, password, and domain to the credentials cache and use
NTLM authentication.
                MyCredentialCache.Add(new Uri(Uri),"Basic", new
System.Net.NetworkCredential(Username,Password,Domain));
               
                //accept ssl certificate
                ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();

                // Create request object and assign credentials.
                Request = (System.Net.HttpWebRequest) HttpWebRequest.Create(Uri);
                Request.CookieContainer = new CookieContainer();
               
                // Set the WebRequest credentials property to the credentials cache.
                Request.Credentials = MyCredentialCache;
               

               if (AuthCookies.Count == 2)
                {
                    Request.CookieContainer.Add(AuthCookies);
                }
                else
                {
                    throw new ApplicationException("Authentication cookies not set.");
               
                }
                switch(Method)
                {
                    case "UNSUBSCRIBE":
                        Request.Method = "UNSUBSCRIBE";
                        Request.Headers.Add("subscription-id",SubscriptionID);
                        break;

                    case "POLL":
                        Request.Method = "POLL";
                        Request.Headers.Add("subscription-id",SubscriptionID);
                        break;

                    case "SUBSCRIBE":
                        Request.Method = "SUBSCRIBE";
                        Request.Headers.Add("Notification-type",NotificationType);
                        Request.Headers.Add("Subscription-lifetime","12000");
                        if(SubscriptionID != "0" && SubscriptionID != "-1")
                        {
                            Request.Headers.Add("subscription-id",SubscriptionID);
                        }
                        Request.Headers.Add("Depth","1");
                        break;
                    case "SEARCH":
                        Request.Method = "SEARCH";
                        //retrieve subject and href for all emails that have an
                        //attachment
                        Body = "<?xml version=\"1.0\"?><D:searchrequest xmlns:D = \"DAV:\" >"
                            + "<D:sql>SELECT \"urn:schemas:httpmail:subject\" FROM \"" + Uri + "\""
                            + "WHERE \"DAV:ishidden\" = false AND \"DAV:isfolder\" = false"
                            + " AND \"urn:schemas:httpmail:hasattachment\" = true"
                            + "</D:sql></D:searchrequest>";

                        Request.ContentType = "text/xml";
                        //Request.Headers.Add("Brief","t");
                        break;
                    case "X-MS-ENUMATTS":
                        Request.Method = "X-MS-ENUMATTS";
                        //Request.Headers.Add("subscription-id",SubscriptionID);
                        Body = "<?xml version=\"1.0\" ?><NoResponse></NoResponse>";
                        Request.Headers.Add("Depth","1,noroot");
                        Request.ContentType = "text/xml";
                        break;
                    case "DELETE":
                        Request.Method = "DELETE";
                        Request.Headers.Add("Depth","infinity");
                        Request.ContentType = "text/xml";
                        break;

                    default:
                        Trace.WriteLine("Warning: Case missed in Action method");
                        Request.Method = Method;
                        Request.Headers.Add("translate","f");
                        Request.ContentType = "text/xml";
                        Request.Headers.Add("Overwrite","t");
                        break;
                }

                // The SUBSCRIBE, POLL, AND UNSUBSCRIBE methods do not
                // require a method request body.
               

                // Encode the body using UTF-8.
               
                    bytes = Encoding.UTF8.GetBytes((string)Body);

                // Set the content header length.
                Request.ContentLength = bytes.Length;
                try
                {

                    Stream newStream = Request.GetRequestStream();
                    newStream.Write(bytes, 0, bytes.Length);

                    newStream.Close();
                }
                catch(Exception ex)
                {
                    Trace.WriteLine("Stact Trace:" + ex.Message +"---"+ ex.StackTrace);
                }

               
            }

           // If the server is not available, the exception will be caught
here.
            catch(Exception ex)
            {
               Trace.WriteLine("Exiting Action with an EXCEPTION when
handling stream: " + ex.Message);
                Trace.WriteLine("Stack Trace: " + ex.StackTrace);
                throw ex;
            }

           try
           {
                  // Call the method and get the response from the server.
               requestResponse = Request.GetResponse();
               if (requestResponse.ContentLength == 0)
               {
                   LastInterpretedResult = (bool)false;
               }

               try
               {
                   // Get the subscription ID.
                   LastSubscriptionID =
requestResponse.Headers.Get("Subscription-ID");
                   if (LastSubscriptionID == null)
                   {
                   LastSubscriptionID = "0";
                   }
               }
               catch
               {
                   // If the SUBSCRIBE method is not being called, then set
LastSubscriptionID
                   // to zero.re
                    LastSubscriptionID = "0";
               }

                // Get returned XML stream.
                Stream ReceiveStream = requestResponse.GetResponseStream();

                //set response stream on object
                LastResponseStream = ReceiveStream;
               

                // Get the utf-8 encoding object.
                Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                StreamReader sr = new StreamReader( ReceiveStream, encode );

                // Read the XML to the end.
                XmlData = sr.ReadToEnd();

               if (XmlData.IndexOf("412 Precondition Failed") > 0)
               {
                   // The POLL method failed.
                   LastSubscriptionID = "-1";
               }

                if (XmlData.IndexOf("Operation timed-out") > 0)
                {
                    LastSubscriptionID = "-1";
                }

                if (XmlData.IndexOf("(440) Login Timeout.") > 0)
                {
                    LastSubscriptionID = "-1";
                }

               if (XmlData.IndexOf("200 OK") > 0)
               {
                   // The WebDAV method succeeded.
                   LastInterpretedResult = (bool)true;
                   LastPollResult = (int)LastPollEnum.NotifyTrue;
               }
               else
               {
                   if (XmlData.IndexOf("No Content") > 0)
                   {
                       LastPollResult = (int)LastPollEnum.NoFolder;
                   }
                   else
                   {
                       LastPollResult = (int)LastPollEnum.NotifyFalse;
                   }
                   LastInterpretedResult = (bool)false;
               }

           }
           catch (Exception ex)
           {
               // A few of the most important and common errors. For more
detail see the
               // SDK documentation.
               //
               // 403 - Forbidden - This means there is not enough access
to create this folder.
               // 405 - Method not allowed - This can mean the user is
overwriting a folder (among
               // other things).
               // 404 - Not found -  This is often used to find out if
something exists.
               // 505 - Server unavailable.
               // 500 - Internal Server Error

               // Throw a clean version of the internal server error.
               if (XmlData.IndexOf("500 Internal Server Error") > 0)
               {
                    throw new ApplicationException("An internal server
error occured, unable to complete request.");
               }

                if (XmlData.IndexOf("Operation timed-out") > 0)
                {
                    LastSubscriptionID = "-1";
                }

                if (XmlData.IndexOf("(440) Login Timeout.") > 0)
                {
                    LastSubscriptionID = "-1";
                }

               Trace.WriteLine("Warning: Exiting Action with an exception:
" + ex.Message );
                Trace.WriteLine("Stack Trace for the excetion: "  + ex.StackTrace );
                //Trace.WriteLine("{0}"+ ex.InnerException);
                Trace.WriteLine("{0}",ex.Source);

               throw ex;
           }

           // Close the response object.
           requestResponse.Close();
           
           // Get the XML response from the WebDAV method call.
           LastResponseXML = XmlData;

            return XmlData;
        }
        // End of Class.
    }

static private CookieCollection DoFormbasedAuthentication(string uri,
NetworkCredential mycred)
        {
            string server;
            HttpWebRequest request;
            HttpWebResponse response;
            byte[] body;
            Stream stream;
            //string result;
           try
           {
               // Get the server portion of the requested uri and appen the
authentication dll from Exchange

               server = uri.Substring(0, uri.IndexOf("/", 8)) +
"/exchweb/bin/auth/owaauth.dll";

               request = GetRequestObject(server, "POST");
               request.CookieContainer = new CookieContainer();
                request.ContentType = "application/x-www-form-urlencoded";
              // Prepare the body of the request
            body =
Encoding.UTF8.GetBytes(string.Format("destination={0}&username={1}\\{2}&password={3}",uri, mycred.Domain, mycred.UserName, mycred.Password));
                    request.ContentLength = body.Length;
                    // Send the request to the server
                    stream = request.GetRequestStream();
                    stream.Write(body, 0, body.Length);
                    stream.Close();
                    // Get the response
                    response = (HttpWebResponse)request.GetResponse();
                    // Check if the login was successful
                    if (response.Cookies.Count < 2) throw
                    new  ApplicationException("Failed to login to OWA. Be sure your domain
and password are correct.");
                    return response.Cookies;
                }
                   catch (ApplicationException ex)           
                {           
                    throw ex;
                }
                catch (Exception ex)
                {
                    throw new Exception("Failed to login to OWA. Username =" +
mycred.UserName + " Password =" + mycred.Password + " domain = " +
mycred.Domain + ".The following error occured: " + ex.Message, ex);
                }
 }

Thanks in advance,
Vijay G
Henning Krause [MVP] - 08 May 2006 16:43 GMT
Hello,

when you get this error, then your login-cookie is expired. You can either
re-login or update your cookie with each response you get...

Greetings,
Henning Krause

> Hi,
>
[quoted text clipped - 347 lines]
> Thanks in advance,
> Vijay G
VJ - 08 May 2006 17:21 GMT
Thank you for your quick response, seems I'm moving in the right direction..

Can you guide me how can I update the cookie with new response.

Thanks,
VJ

> Hello,
>
[quoted text clipped - 288 lines]
> > Trace.WriteLine("Stack Trace for the excetion: "  + ex.StackTrace );
> > //Trace.WriteLine("{0}"+ ex.InnerException);
Henning Krause [MVP] - 08 May 2006 23:37 GMT
Hello,

when you send your authentication cookies along a request in the
cookie-collection, the response should also contain new cookies. You can use
those cookies for further requests... this should keep  ypur session alive.

Greetings,
Henning Krause

> Thank you for your quick response, seems I'm moving in the right
> direction..
[quoted text clipped - 305 lines]
>> > Trace.WriteLine("Stack Trace for the excetion: "  + ex.StackTrace );
>> > //Trace.WriteLine("{0}"+ ex.InnerException);
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.