Contents tagged with .Net C# Exchange Calendar items

  • Getting calendar items using Exchange Web Services

    I am no expert at exchange, let alone Exchange Web Services (EWS), but I recently had to use it to get at calendar information for a project. Let me tell you that the documentation for EWS sucks and the API is not very intuitive. That said, I was able to piece together what I needed. The code is not perfect and could definitely use a good once over by someone with more than 2 days experience.

    The code will show how to get at calendar items, how to use a date range and how to get the body of the calendar item. I racked my brain for a while to get the body - you have  to make a call to get the calendar items and then for each item you have to go and use the ID to get its body in another call. The  idea is that the first call gets only the small parts of an item. If you want things like attachments then you make another call to get it. Here is a link to an article that gets into it.

    The code is not perfect but I want to save someone the time that I spent. Please leave comments with suggestions and improvements.

    UPDATE: I have attached some code. I don’t have access to an exchange server. It compiles but at least the classes are there for you. 

    private List<CalendarInfo> GetCalendarEvents()
    {
        List<CalendarInfo> calendarEvents = new List<CalendarInfo>();

        ExchangeServiceBinding esb =
            new ExchangeHelper().GetExchangeBinding("myUserName", "myPassword", "myDomain");

        // Form the FindItem request.
       
    FindItemType findItemRequest = new FindItemType();

        CalendarViewType calendarView = new CalendarViewType();
        calendarView.StartDate = DateTime.Now.AddDays(-1);
        calendarView.EndDate = DateTime.Now.AddDays(1);
        calendarView.MaxEntriesReturned = 100;
        calendarView.MaxEntriesReturnedSpecified = true;

        findItemRequest.Item = calendarView;

        // Define which item properties are returned in the response.
       
    ItemResponseShapeType itemProperties = new ItemResponseShapeType();
        // Use the Default shape for the response.
        //itemProperties.BaseShape = DefaultShapeNamesType.IdOnly;
       
    itemProperties.BaseShape = DefaultShapeNamesType.AllProperties;
        findItemRequest.ItemShape = itemProperties;

        DistinguishedFolderIdType[] folderIDArray =
            new DistinguishedFolderIdType[1];
        folderIDArray[0] = new DistinguishedFolderIdType();
        folderIDArray[0].Id = DistinguishedFolderIdNameType.calendar;

        if (!string.IsNullOrEmpty(criteria.EmailAddress))
        {
            folderIDArray[0].Mailbox = new EmailAddressType();
            folderIDArray[0].Mailbox.EmailAddress = "myEmail.com";
        }
       
        findItemRequest.ParentFolderIds = folderIDArray;

        // Define the traversal type.
       
    findItemRequest.Traversal = ItemQueryTraversalType.Shallow;

        try
       
    {
            // Send the FindItem request and get the response.
           
    FindItemResponseType findItemResponse =
                esb.FindItem(findItemRequest);

            // Access the response message.
           
    ArrayOfResponseMessagesType responseMessages =
                findItemResponse.ResponseMessages;
            ResponseMessageType[] rmta = responseMessages.Items;

            int folderNumber = 0;

            foreach (ResponseMessageType rmt in rmta)
            {
                // One FindItemResponseMessageType per folder searched.
               
    FindItemResponseMessageType firmt =
                    rmt as FindItemResponseMessageType;

                if (firmt.RootFolder == null)
                    continue ;

                FindItemParentType fipt = firmt.RootFolder;
                object obj = fipt.Item;

                // FindItem contains an array of items.
               
    if (obj is ArrayOfRealItemsType)
                {
                    ArrayOfRealItemsType items =
                        (obj as ArrayOfRealItemsType);
                    if (items.Items == null)
                    {
                        folderNumber++;
                    }
                    else
                   
    {
                        foreach (ItemType it in items.Items)
                        {

                            if (it is CalendarItemType)
                            {
                                CalendarItemType cal = (CalendarItemType)it;
                                CalendarInfo ce = new CalendarInfo();

                                ce.Location = cal.Location;
                                ce.StartTime = cal.Start;
                                ce.EndTime = cal.End;
                                ce.Subject = cal.Subject;
                                ce.Body = GetMeetingBody(esb, cal);

                                calendarEvents.Add(ce);
                            }

                        }

                        folderNumber++;
                    }
                }
            }

        }
        catch (Exception e)
        {
            throw;
        }
        finally
       
    {
           
        }

        return calendarEvents;
    }

    private string GetMeetingBody(ExchangeServiceBinding binding, CalendarItemType meeting)
    {
        string meetingBody = string.Empty;
        CalendarItemType temp = null;

        // Call GetItem on each ItemId to retrieve the
        // item’s Body property and any AttachmentIds.
        //
        // Form the GetItem request.
       
    GetItemType getItemRequest = new GetItemType();

        getItemRequest.ItemShape = new ItemResponseShapeType();
        // AllProperties on a GetItem request WILL return
        // the message body.
       
    getItemRequest.ItemShape.BaseShape =
            DefaultShapeNamesType.AllProperties;

        getItemRequest.ItemIds = new ItemIdType[1];
        getItemRequest.ItemIds[0] = (BaseItemIdType)meeting.ItemId;

        // Here is the call to exchange.
       
    GetItemResponseType getItemResponse =
            binding.GetItem(getItemRequest);

        // We only passed in one ItemId to the GetItem
        // request. Therefore, we can assume that
        // we got at most one Item back.
       
    ItemInfoResponseMessageType getItemResponseMessage =
            getItemResponse.ResponseMessages.Items[0]
            as ItemInfoResponseMessageType;

        if (getItemResponseMessage != null)
        {
            if (getItemResponseMessage.ResponseClass ==
                ResponseClassType.Success
                && getItemResponseMessage.Items.Items != null
               
    && getItemResponseMessage.Items.Items.Length > 0)
            {
                temp = (CalendarItemType)getItemResponseMessage.Items.Items[0];

                if (temp.Body != null)
                    meetingBody = temp.Body.Value;
            }
        }

        return meetingBody;
    }

    private ExchangeServiceBinding GetExchangeBinding(
          string userName, string passwotrd, string domain)
      {
    
          ExchangeServiceBinding binding = new ExchangeServiceBinding();
    
          ServicePointManager.ServerCertificateValidationCallback =
                  delegate(Object obj, X509Certificate certificate, 
                  X509Chain chain, SslPolicyErrors errors)
                  {
                      // Replace this line with code to validate server certificate.
                      return true;
                  };
    
          System.Net.WebProxy proxyObject = 
              new System.Net.WebProxy();
          proxyObject.Credentials = 
              System.Net.CredentialCache.DefaultCredentials;
    
          binding.Credentials = 
              new NetworkCredential(userName, password, domain);
     
          string server = ConfigurationManager.AppSettings["ExchangeServer"] as string;
    
          if (server == null || string.IsNullOrEmpty(server))
              throw new ArgumentNullException("The Exchange server Url could not be found.");
    
          binding.Url = server;
          Console.WriteLine("***** " + server);
    
          binding.Proxy = proxyObject;
    
          return binding;
      }

    Read more...