How to work with items on an Exchange Server computer by using HttpWebRequest in Visual Basic .NET (314191)



The information in this article applies to:

  • Microsoft Exchange 2000 Server
  • Microsoft Visual Basic .NET (2002)
  • Microsoft Visual Basic .NET (2003)
  • Microsoft XML 3.0
  • Microsoft XML 4.0

This article was previously published under Q314191

INTRODUCTION

This article contains code samples that perform the following tasks on a computer that is running Microsoft Exchange 2000 Server:
  • Create an Appointment item
  • Search for items
  • Copy and move objects
The code samples use the HttpWebRequest class and the HttpWebResponse class from the System.Net namespace.

back to the top

MORE INFORMATION

To use the HttpWebRequest class and the HttpWebResponse class to work with items in Exchange 2000 Server:
  1. Start Microsoft Visual Studio .NET.
  2. On the File menu, point to New, and then click Project.
  3. Under Project Types, click Visual Basic Projects.
  4. Under Templates, click Console Application, and then click OK.

    By default, Module1.vb is created.
  5. In the code window, replace the existing code with one of the code samples in this article.
  6. Search for "TODO" in the code, and then modify the code for your environment.
  7. Press F5 to build and to run the program.
back to the top

Create an Appointment item

To create an Appointment item, set the HttpWebRequest.Method property to "PROPPATCH," send the request to the Exchange Server computer, and then use the HttpWebResponse class to receive the response.
Imports System.Net
Imports System.IO

Module Module1
    Sub Main()
        ' TODO: Replace the following URL with the URL to the new Appointment item. 
        Dim sUri As String = "http://ExchServer/Exchange/Administrator/Calendar/Test.eml"

        Dim myUri As System.Uri = New System.Uri(sUri)
        Dim HttpWRequest As HttpWebRequest = WebRequest.Create(myUri)

        Dim strXMLNSInfo As String = "xmlns:g=""DAV:"" " & _
         " xmlns:e=""http://schemas.microsoft.com/exchange/""" & _
         " xmlns:mapi=""http://schemas.microsoft.com/mapi/""" & _
         " xmlns:x=""xml:"" xmlns:cal=""urn:schemas:calendar:""" & _
         " xmlns:dt=""urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/""" & _
         " xmlns:mail=""urn:schemas:httpmail:"">"

        Dim sQuery As String = "<?xml version=""1.0""?>" & _
         "<g:propertyupdate " & strXMLNSInfo & _
         "<g:set>" & _
         "<g:prop>" & _
         "<g:contentclass>urn:content-classes:appointment</g:contentclass>" & _
         "<e:outlookmessageclass>IPM.Appointment</e:outlookmessageclass>" & _
         "<mail:subject>Appointment Subject</mail:subject>" & _
         "<cal:location>Appointment Location</cal:location>" & _
         "<cal:dtstart dt:dt=""dateTime.tz"">2002-01-07T22:00:00.000Z</cal:dtstart>" & _
         "<cal:dtend dt:dt=""dateTime.tz"">2002-01-07T22:30:00.000Z</cal:dtend>" & _
         "<cal:instancetype dt:dt=""int"">0</cal:instancetype>" & _
         "<cal:busystatus>BUSY</cal:busystatus>" & _
         "<cal:meetingstatus>TENTATIVE</cal:meetingstatus>" & _
         "<cal:alldayevent dt:dt=""boolean"">0</cal:alldayevent>" & _
         "</g:prop>" & _
         "</g:set>" & _
         "</g:propertyupdate>"

        ' Set credentials.
        ' TODO: Replace the following with appropriate user credentials.
        Dim myCred As NetworkCredential = New NetworkCredential("Domain\UserName", "Password")
        Dim MyCredentialCache As CredentialCache = New CredentialCache()
        MyCredentialCache.Add(myUri, "Basic", myCred)
        HttpWRequest.Credentials = MyCredentialCache

        ' Set headers.
        HttpWRequest.KeepAlive = False
        HttpWRequest.Headers.Set("Pragma", "no-cache")
        HttpWRequest.Headers.Set("Translate", "f")
        HttpWRequest.ContentType = "text/xml"
        HttpWRequest.ContentLength = sQuery.Length

        'Set the request timeout to 5 minutes.
        HttpWRequest.Timeout = 300000
        ' set the request method
        HttpWRequest.Method = "PROPPATCH"

        ' Store the data in a byte array.
        Dim ByteQuery() As Byte = System.Text.Encoding.ASCII.GetBytes(sQuery)
        HttpWRequest.ContentLength = ByteQuery.Length
        Dim QueryStream As Stream = HttpWRequest.GetRequestStream()
        ' Write the data to be posted to the Request stream.
        QueryStream.Write(ByteQuery, 0, ByteQuery.Length)
        QueryStream.Close()

        ' Send the request and get a response.
        Dim HttpWResponse As HttpWebResponse = HttpWRequest.GetResponse()

        ' Get the status and the headers.
        Dim iStatCode As Integer = HttpWResponse.StatusCode
        Dim sStatus As String = iStatCode.ToString()
        Console.WriteLine("Status: {0} {1}", sStatus, HttpWResponse.StatusDescription.ToString())

        Console.WriteLine("Request Headers:")
        Console.WriteLine(HttpWRequest.Headers.ToString())
        Console.WriteLine("Response Headers:")
        Console.WriteLine(HttpWResponse.Headers.ToString())

        ' Get the Response stream.
        Dim strm As Stream = HttpWResponse.GetResponseStream()

        ' Read the Response stream.
        Dim sr As StreamReader = New StreamReader(strm)
        Dim sText As String = sr.ReadToEnd()
        Console.WriteLine("Response: {0}", sText)

        ' Close the stream.
        strm.Close()

        ' Clean up.
        HttpWRequest = Nothing
        HttpWResponse = Nothing
        MyCredentialCache = Nothing
        myCred = Nothing
        strm = Nothing
        sr = Nothing
    End Sub
End Module
back to the top

Search for items

To search for items, set the HttpWebRequest.Method property to "SEARCH," send the query string to the Exchange server in a request, and then use the HttpWebResponse class to receive the response. The query string looks similar to Transact-SQL.
Imports System.Net
Imports System.IO

Module Module1
    Sub Main()
        ' TODO: Replace the following URL with the URL of an object on the Exchange Server computer.
        Dim sUri As String = "http://ExchServer/Exchange/Administrator/Inbox/"

        Dim myUri As System.Uri = New System.Uri(sUri)
        Dim HttpWRequest As HttpWebRequest = WebRequest.Create(myUri)

        ' TODO: Search for items whose subject is Test.
        Dim sQuery As String
        sQuery = "<?xml version='1.0'?>" & _
         "<g:searchrequest xmlns:g='DAV:' >" & _
         "<g:sql>SELECT ""DAV:displayname"", " & _
         """DAV:href"" " & _
         "FROM SCOPE('SHALLOW TRAVERSAL OF """ & sUri & """')" & _
         "WHERE ""urn:schemas:mailheader:subject"" = 'Test'" & _
         "</g:sql>" & _
         "</g:searchrequest>"

        ' Set credentials.
        ' TODO: Replace the following with appropriate user credentials.
        Dim myCred As NetworkCredential = New NetworkCredential("Domain\UserName", "Password")
        Dim MyCredentialCache As CredentialCache = New CredentialCache()
        MyCredentialCache.Add(myUri, "Basic", myCred)
        HttpWRequest.Credentials = MyCredentialCache

        ' Set some headers.
        HttpWRequest.KeepAlive = False
        HttpWRequest.Headers.Set("Pragma", "no-cache")

        HttpWRequest.Headers.Set("Translate", "f")
        HttpWRequest.Headers.Set("Depth", "0")
        HttpWRequest.ContentType = "text/xml"
        HttpWRequest.ContentLength = sQuery.Length

        'Set the request timeout to 5 minutes.
        HttpWRequest.Timeout = 300000
        ' set the request method
        HttpWRequest.Method = "SEARCH"

        ' Store the data in a byte array.
        Dim ByteQuery() As Byte = System.Text.Encoding.ASCII.GetBytes(sQuery)
        HttpWRequest.ContentLength = ByteQuery.Length
        Dim QueryStream As Stream = HttpWRequest.GetRequestStream()
        ' write the data to be posted to the Request Stream
        QueryStream.Write(ByteQuery, 0, ByteQuery.Length)
        QueryStream.Close()

        ' Send the request and get a response.
        Dim HttpWResponse As HttpWebResponse = HttpWRequest.GetResponse()

        ' Get the status and the headers.
        Dim iStatCode As Integer = HttpWResponse.StatusCode
        Dim sStatus As String = iStatCode.ToString()
        Console.WriteLine("Status: {0} {1}", sStatus, HttpWResponse.StatusDescription.ToString())

        Console.WriteLine("Request Headers:")
        Console.WriteLine(HttpWRequest.Headers.ToString())
        Console.WriteLine("Response Headers:")
        Console.WriteLine(HttpWResponse.Headers.ToString())

        ' Get the Response stream.
        Dim strm As Stream = HttpWResponse.GetResponseStream()

        ' Read the Response stream.
        Dim sr As StreamReader = New StreamReader(strm)
        Dim sText As String = sr.ReadToEnd()
        Console.WriteLine("Response: {0}", sText)

        ' Close the stream.
        strm.Close()

        ' Clean up.
        HttpWRequest = Nothing
        HttpWResponse = Nothing
        MyCredentialCache = Nothing
        myCred = Nothing
        QueryStream = Nothing
        strm = Nothing
        sr = Nothing
    End Sub
End Module
back to the top

Copy and move objects

To copy or to move objects, create an HttpWebRequest object that is based on the source uniform resource identifier (URI), set the HttpWebRequest.Method property to "COPY" or to "MOVE," put the destination URI in the header of the request, and then send the request to the Exchange Server computer. Use the HttpWebResponse class to receive the response.
Imports System.Net
Imports System.IO

Module Module1

    Sub Main()
        ' TODO: Replace the following with True for MOVE, or False for COPY.
        Dim bMove As Boolean = True

        ' TODO: Replace the following with the source URL. 
        Dim sSourceURL As String = "http://ExchServer/Public/Folder1/Test.EML"

        ' TODO: Replace the following with the destination URL.
        Dim sDestinationURL As String = "http://ExchServer/Public/Folder2/Test.EML"


        Dim myUri As System.Uri = New System.Uri(sSourceURL)
        Dim HttpWRequest As HttpWebRequest = WebRequest.Create(myUri)

        ' Set the credentials.
        ' TODO: Replace the following with appropriate user credentials.
        Dim myCred As NetworkCredential = New NetworkCredential("Domain\UserName", "Password")
        Dim MyCredentialCache As CredentialCache = New CredentialCache()
        MyCredentialCache.Add(myUri, "Basic", myCred)
        HttpWRequest.Credentials = MyCredentialCache

        ' Set headers.
        HttpWRequest.KeepAlive = False
        HttpWRequest.Headers.Set("Pragma", "no-cache")
        HttpWRequest.Headers.Set("Destination", sDestinationURL)

        'Set the request timeout to 5 minutes.
        HttpWRequest.Timeout = 300000
        ' Set the Request method.
        If bMove Then
            HttpWRequest.Method = "MOVE"
        Else
            HttpWRequest.Method = "COPY"
        End If

        ' Send the request and get the response.
        Dim HttpWResponse As HttpWebResponse = HttpWRequest.GetResponse()

        ' Get the status and the headers.
        Dim iStatCode As Integer = HttpWResponse.StatusCode
        Dim sStatus As String = iStatCode.ToString()
        Console.WriteLine("Status: {0} {1}", sStatus, HttpWResponse.StatusDescription.ToString())

        Console.WriteLine("Request Headers:")
        Console.WriteLine(HttpWRequest.Headers.ToString())
        Console.WriteLine("Response Headers:")
        Console.WriteLine(HttpWResponse.Headers.ToString())

        ' Get the Response stream.
        Dim strm As Stream = HttpWResponse.GetResponseStream()

        ' Read the Response stream.
        Dim sr As StreamReader = New StreamReader(strm)
        Dim sText As String = sr.ReadToEnd()
        Console.WriteLine("Response: {0}", sText)

        ' Close the stream.
        strm.Close()

        ' Clean up.
        HttpWRequest = Nothing
        HttpWResponse = Nothing
        MyCredentialCache = Nothing
        myCred = Nothing
        strm = Nothing
        sr = Nothing
    End Sub
End Module
back to the top

Modification Type:MajorLast Reviewed:6/10/2005
Keywords:kbHOWTOmaster kbhowto KB314191 kbAudDeveloper