exchange ma pi

17
Hands-On Lab Getting Started with the EWS Managed API 1.0 Lab version: 1.0 Last updated: 12/17/2010

Upload: javier-gallardo

Post on 24-Apr-2015

91 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Exchange Ma Pi

Hands-On Lab

Getting Started with the EWS Managed API 1.0

Lab version: 1.0

Last updated: 12/17/2010

Page 2: Exchange Ma Pi

CONTENTS

OVERVIEW ............................................................................................................................................. 3 System Requirements 3

EXERCISE 1: WORKING WITH CALENDAR ITEMS .............................................................................. 3 Task 1 – Beginning the Lab ............................................................................................................... 3

Task 2 – Establishing a connection to the Exchange Server ............................................................... 4

Task 3 – Creating Items .................................................................................................................... 4

Task 4 – Finding Items ...................................................................................................................... 6

Task 5 – Impersonation .................................................................................................................... 7

EXERCISE 2: WORKING WITH EXTENDED PROPERTIES ................................................................... 8 Task 1 – Beginning the Exercise ........................................................................................................ 8

Task 2 – Create Items and Extended Properties................................................................................ 9

Task 3 – Finding Items with Extended Properties.............................................................................. 9

EXERCISE 3: WORKING WITH THE EXCHANGE FREE-BUSY SERVICE .......................................... 10 Task 1 – Beginning the Exercise ...................................................................................................... 10

Task 2 – Querying the Free-Busy Service ........................................................................................ 11

EXERCISE 4: WORKING WITH EXCHANGE PUSH NOTIFICATIONS ................................................. 13 Task 1 – Beginning the Exercise ...................................................................................................... 13

Task 2 – Creating the Push Notification Listener ............................................................................. 13

Task 3 – Subscribing for Push Notifications .................................................................................... 14

Task 4 – Processing Push Notifications ........................................................................................... 15

SUMMARY ............................................................................................................................................ 16

Page 3: Exchange Ma Pi

Overview

Lab Time: 45 minutes

Lab Folder: C:\%UC14TrainingKit%\Labs\5\Source\Before

The After folder contains the completed lab exercises.

Lab Overview: The Microsoft Exchange Web Services (EWS) Managed API 1.0 provides an intuitive

managed API for developing client and server applications that leverage Exchange 2010 data and

business logic, whether Exchange is running on premises or in the cloud. The EWS Managed API 1.0

makes Exchange Web Services SOAP calls “under the covers”, so many environments are already

configured for EWS Managed API 1.0.

In this lab, you will use the EWS Managed API 1.0 to:

Prepare the API to connect to the correct Exchange CAS server for your calling user.

Work with mailbox items.

Find mailbox items using the example of retrieving appointments.

Impersonate users so work done with the API is done using the impersonated user’s credentials.

Apply extended properties to mailbox items.

Perform complex searches for mailbox items with a specific extended property.

Work with Exchange business logic services such as the Free-Busy Service.

Subscribe to and listen for push notifications.

System Requirements

You must have the following items to complete this lab:

Microsoft Visual Studio 2010

Exchange Web Services Managed API 1.0 SDK

Two accounts configured to have Microsoft Exchange mailboxes, referred to as the primary and

secondary lab users in this lab.

Exercise 1: Working with Calendar Items

Task 1 – Beginning the Lab

Page 4: Exchange Ma Pi

In this task, you will open the project and configure it to run with your accounts.

1. Navigate to Start >> All Programs >> Microsoft Visual Studio 2010.

2. Click on the Microsoft Visual Studio 2010 icon to start Visual Studio 2010.

3. Select File >> Open Project.

4. Navigate to the folder

C:\%UC14TrainingKit%\Labs\5\Source\Before\GettingStartedwithEWSMA.sln.

5. In the Solution Explorer, right-click the EWSMA_Calendars project and select Set as StartUp

Project.

6. Open the EWSMA_Calendars project.

7. In Solution Explorer, open the app.config file.

8. Change the PrimaryLabUserId and SecondaryLabUserId values to your primary and

secondary lab accounts.

9. Open the Program.cs file.

10. Select View >> Task List and select Comments from the menu.

Task 2 – Establishing a connection to the Exchange Server

In this task, you will create an ExchangeService object and connect to the correct Exchange CAS Server

using your default credentials and your primary lab user ID.

1. In the Task List, navigate to TODO: 5.1.1.

2. Add the following code after the TODO: 5.1.1 comment. This creates the object reference to

Exchange Web Services.

C#

private static ExchangeService _service;

3. Navigate to TODO: 5.1.2.

4. Add the following code after the TODO: 5.1.2 comment. This uses AutoDiscover to find the

most efficient Client Access Server for the primary lab user’s mailbox.

C#

_service = new ExchangeService(ExchangeVersion.Exchange2010);

_service.UseDefaultCredentials = true;

_service.AutodiscoverUrl(_primaryLabUserId);

Task 3 – Creating Items

Page 5: Exchange Ma Pi

In this task, you will create an appointment, set properties to add an attendee, set a recurrence pattern,

save the appointment, and send the invitation.

1. Navigate to TODO: 5.1.3.

2. Add the following code after the TODO: 5.1.3 comment. This creates an Appointment, sets

its basic properties, and sets an advanced property like the recurrence pattern.

C#

Appointment appointment = new Appointment(_service);

appointment.Subject = _companyName + " introduction to EWS";

appointment.Body = "Weekly status with " + _companyName;

appointment.RequiredAttendees.Add(_secondaryLabUserId);

appointment.Start = new

DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,DateTime.

Now.AddHours(1).Hour, 0, 0);

appointment.End = appointment.Start.AddHours(1);

DayOfTheWeek dayOfTheWeek = (DayOfTheWeek)Enum.Parse(

typeof(DayOfWeek), appointment.Start.DayOfWeek.ToString());

appointment.Recurrence = new Recurrence.WeeklyPattern(

appointment.Start.Date,

1, // Repeat every 1 week

dayOfTheWeek);

appointment.Save(SendInvitationsMode.SendToAllAndSaveCopy);

3. Go to Debug >> Start Without Debugging or use the shortcut key combination by pressing

[CTRL]+[F5] to start the application.

4. Press “1” to create a recurring calendar appointment.

5. Open Microsoft Outlook 2010 and navigate to the Calendar.

Page 6: Exchange Ma Pi

6. Verify that an appointment has been created an hour from the current time and that it

recurs on the same day and time next week.

7. Close the console application.

Task 4 – Finding Items

In this task, you will search the primary lab user’s calendar for appointments occurring in the next five

days.

1. Navigate to TODO: 5.1.4.

2. Un-comment code surrounded by /* … */ block.

3. Add the following code after the TODO: 5.1.4 comment. This searches for all appointments

in the Calendar folder that fall into the date range specified by the CalendarView.

C#

CalendarView calendarView = new CalendarView(DateTime.Now,

DateTime.Now.AddDays(numberOfDays));

FindItemsResults<Appointment> appointments =

_service.FindAppointments(

WellKnownFolderName.Calendar,

calendarView);

4. Go to Debug >> Start Without Debugging or [CTRL]+[F5] to start the application.

5. Press “2” to view the primary lab user’s appointments for the next five days.

Page 7: Exchange Ma Pi

6. Return to Outlook 2010, and verify that all of the appointments in the next five days are

displayed in the console.

7. Close the console application.

Task 5 – Impersonation

Task Setup Requirements

In order to complete the this lab, you’ll need to grant the ApplicationImpersonation role to the primary

lab user account over the secondary lab user account.

Open the Exchange Management Shell as an administrator on the Exchange Server and run the

following command where -Name is a unique name for the role, -User is the primary lab user Id, and -

RecipientOrganizationalUnitScope is the organizational unit containing the secondary lab user account.

New-ManagementRoleAssignment –Name “Impersonation-SeanChai” –Role

“ApplicationImpersonation” –User sc –RecipientOrganizationalUnitScope

fabrikam.com\OUs\Users\Sales

Follow this link for more information http://msdn.microsoft.com/en-us/library/bb204095.aspx

In this task, you will set the Exchange Service to impersonate the secondary lab user and create an

appointment using their credentials.

1. Navigate to TODO: 5.1.5.

2. Un-comment code surrounded by /* … */ block.

3. Add the following code after the TODO: 5.1.5 comment. This sets the ExchangeService to

impersonate the secondary lab user, enabling you to perform operations against Exchange

Server using the secondary lab user’s identity and permissions.

C#

Page 8: Exchange Ma Pi

_service.ImpersonatedUserId = new ImpersonatedUserId(

ConnectingIdType.SmtpAddress,

_secondaryLabUserId);

4. Go to Debug >> Start Without Debugging or [CTRL]+[F5] to start the application.

5. Press “3” to impersonate the secondary lab user and create an appointment.

6. Open Outlook 2010, open Calendar and verify that the primary lab user receives an

appointment invitation from the secondary lab user.

7. Close the console application.

8. Close Outlook 2010.

Exercise 2: Working with Extended

Properties

Task 1 – Beginning the Exercise

In this task, you will open the project and configure it to run with your accounts.

1. In the Solution Explorer, right-click the EWSMA_ExtendedProperties project and select Set

as StartUp Project.

2. Open the EWSMA_ExtendedProperties project.

3. In Solution Explorer, open the app.config file.

4. Change the PrimaryLabUserId and SecondaryLabUserId values to your primary and

secondary lab accounts.

Page 9: Exchange Ma Pi

Task 2 – Create Items and Extended Properties

In this task, you will create an extended property, attach it to an appointment, and set its value.

1. Navigate to TODO: 5.2.1.

2. Add the following code after the TODO: 5.2.1 comment. This defines a “Customer ID”

property for an appointment and assigns the property the value “12345”.

C#

ExtendedPropertyDefinition extendedProperty = new

ExtendedPropertyDefinition(

DefaultExtendedPropertySet.Appointment,

_extendedPropertyName,

MapiPropertyType.String);

appointment.SetExtendedProperty(extendedProperty, _customerId);

appointment.Save(SendInvitationsMode.SendToAllAndSaveCopy);

Task 3 – Finding Items with Extended Properties

In this task, you will use the Extended Property defined above to find the Appointment you created.

1. Navigate to TODO: 5.2.2.

2. Un-comment code surrounded by /* … */ block to display the search results.

3. Add the following code after the TODO: 5.2.2 comment. This finds all appointments in your

Calendar with the “Customer ID” extended property.

C#

ItemView itemView = new ItemView(10);

ExtendedPropertyDefinition extendedProperty =

new ExtendedPropertyDefinition(

DefaultExtendedPropertySet.Appointment,

_extendedPropertyName,

MapiPropertyType.String);

itemView.PropertySet = new PropertySet(

BasePropertySet.IdOnly,

ItemSchema.Subject,

AppointmentSchema.Start,

AppointmentSchema.End,

extendedProperty);

SearchFilter filter = new SearchFilter.Exists(extendedProperty);

FindItemsResults<Item> appointments =_service.FindItems(

WellKnownFolderName.Calendar,

filter,

Page 10: Exchange Ma Pi

itemView);

4. Go to Debug >> Start Without Debugging or press [CTRL]+[F5] to start the application.

5. Press “1” to create an appointment with the “Customer ID” extended property.

6. Open Outlook 2010 and verify that the appointment is in the Calendar. The extended

property is not visible in Outlook.

7. Press “2” to view appointments with the “Customer ID” extended property.

8. Verify that the appointment created previously displays with the “Customer ID” value of

“General Industries”.

Close the console application.

Exercise 3: Working with the Exchange

Free-Busy Service

Task 1 – Beginning the Exercise

In this task, you will open the project and configure it to run with your accounts.

1. In the Solution Explorer, right-click the EWSMA_FreeBusy project and select Set as StartUp

Project.

2. Open the EWSMA_ExtendedProperties project.

3. In Solution Explorer, open the app.config file.

4. Change the PrimaryLabUserId and SecondaryLabUserId values to your primary and

secondary lab accounts.

Page 11: Exchange Ma Pi

5. Open Outlook 2010 and create three appointments in the primary lab user’s Calendar

throughout the day.

6. Start a remote desktop session as the secondary lab user.

7. Open Outlook 2010 and create three appointments in the secondary lab user’s Calendar

throughout the day. Make sure one of them overlaps with one of the primary lab user’s

appointments.

Task 2 – Querying the Free-Busy Service

In this task, you will query the free-busy service to find available appointment times with the secondary

lab user.

1. Navigate to TODO: 5.3.1.

2. Add the following code after the TODO: 5.3.1 comment. This creates a list of users for

whom you want to query availability information.

C#

List<AttendeeInfo> attendees = new List<AttendeeInfo>();

attendees.Add(new AttendeeInfo()

{

SmtpAddress = _primaryLabUserId,

AttendeeType = MeetingAttendeeType.Organizer

});

attendees.Add(new AttendeeInfo()

{

SmtpAddress = _secondaryLabUserId,

AttendeeType = MeetingAttendeeType.Required

});

3. Navigate to TODO: 5.3.2.

4. Add the following code after the TODO: 5.3.2 comment. This define the requirements for

the and to call the free-busy service.

C#

AvailabilityOptions options = new AvailabilityOptions();

options.MeetingDuration = 60;

options.MaximumNonWorkHoursSuggestionsPerDay = 4;

options.MinimumSuggestionQuality = SuggestionQuality.Good;

options.RequestedFreeBusyView = FreeBusyViewType.FreeBusy;

GetUserAvailabilityResults results =

_service.GetUserAvailability(

Page 12: Exchange Ma Pi

attendees,

new TimeWindow(DateTime.Now, DateTime.Now.AddDays(1)),

AvailabilityData.FreeBusyAndSuggestions,

options);

5. Un-comment code surrounded by /* … */ block to display the results of the free-busy

service query.

6. Go to Debug >> Start Without Debugging or [Ctrl]+[F5] to start the application.

7. The console will display a list of suggested appointment times and their quality.

8. Open the primary lab user’s calendar in Outlook 2010 and verify that the time slots during

the suggested meeting times do not conflict with any appointments.

9. Open the secondary lab user’s calendar in Outlook 2010 and verify that the time slots during

the suggested meeting times do not conflict with any appointments.

10. Choose one of the suggested meeting times.

11. Open your Outlook calendar to verify that the appointment was scheduled.

Page 13: Exchange Ma Pi

12. Close the console application.

TimeWindow must span into the next day or the GetUserAvailability call will throw an exception.

Exercise 4: Working with Exchange Push

Notifications

Task 1 – Beginning the Exercise

In this task, you will open the project and configure it to run with your accounts.

1. In the Solution Explorer, right-click the PushNotifications project and select Set as StartUp

Project.

2. Open the PushNotifications project.

3. In Solution Explorer, open the App.config file.

4. Change the PrimaryLabUserId value to your primary lab account.

5. Start a remote desktop session as the secondary lab user.

Task 2 – Creating the Push Notification Listener

In this task, you will create and start a WCF service that listens for push notifications from the Exchange

Server.

1. Navigate to TODO: 5.4.1.

2. Add the following code after the TODO: 5.4.1 comment to create the WCF service and pass

its URI to the subscribe method.

C#

var listener = new PushNotificationListener();

SubscribeForPushNotifications(listener.LocalEndpoint);

3. Navigate to TODO: 5.4.2.

4. Add the following code after the TODO: 5.4.2 comment. This creates a dynamic Uri for the

WCF service. Using a dynamically generated Uri for the push notification listener enables

your application to create a unique push notification listener endpoint for every user or

subscription.

Page 14: Exchange Ma Pi

C#

UriBuilder uriBuilder = new UriBuilder

{

Scheme = Uri.UriSchemeHttp,

Host = properties.HostName,

Path = Guid.NewGuid().ToString(),

Port = 80

};

5. Remove the comments /* .. */ from around the commented block of code.

6. Navigate to TODO: 5.4.3.

7. Add the following code after the TODO: 5.4.3 comment. This makes the push notification

listener implement the Microsoft.Exchange.Notifications.INotificationServicePortType

service contract, in order to receive and process push notifications from Exchange Server.

C#

_serviceHost.AddServiceEndpoint(

typeof(INotificationServicePortType),

new BasicHttpBinding(BasicHttpSecurityMode.None),

string.Empty);

Task 3 – Subscribing for Push Notifications

In this task, you will specify the folders and events to receive push notifications for. You will also specify

the URL that the notifications should be sent to.

1. Navigate to TODO: 5.4.4.

2. Add the following code after the TODO: 5.4.4 comment. This creates the subscription object

that will be returned by the Exchange Service.

C#

PushSubscription pushSubscription;

3. Navigate to TODO: 5.4.5.

4. Add the following code after the TODO: 5.4.5 comment to create a list of folders for which

you would like to get notifications.

C#

var folderIds = new List<FolderId>()

{

WellKnownFolderName.Inbox,

WellKnownFolderName.Calendar

};

Page 15: Exchange Ma Pi

5. Navigate to TODO: 5.4.6.

6. Add the following code after the TODO: 5.4.6 comment. This creates the list of events for

which you would like to get notifications.

C#

var eventTypes = new List<EventType>();

eventTypes.Add(EventType.NewMail);

eventTypes.Add(EventType.Deleted);

eventTypes.Add(EventType.Moved);

eventTypes.Add(EventType.Created);

eventTypes.Add(EventType.Modified);

7. Navigate to TODO: 5.4.7.

8. Add the following code after the TODO: 5.4.7 comment. This subscribes to the push

notifications on the Exchange Server and specifies the URL that the notifications should be

sent to, the frequency in minutes which the Exchange Server should contact the endpoint,

and the events to subscribe to.

C#

pushSubscription = _service.SubscribeToPushNotifications(

folderIds,

new Uri(listenerEndpoint),

1,

null,

eventTypes.ToArray());

9. Remove the comments /* .. */ from around the commented block of code.

Task 4 – Processing Push Notifications

In this task, you will process the push notifications sent by the Exchange Server and notify the server

whether or not the subscription should be expired.

1. Navigate to TODO: 5.4.8.

2. Add the following code after the TODO: 5.4.8 comment. This iterates through the

notification events and outputs the type of event and when it occurred.

C#

foreach (BaseNotificationEventType notificationEvent

in message.Notification.Items)

{

var mailEvent =

notificationEvent as BaseObjectChangedEventType;

Console.WriteLine(string.Format("{0} at {1}",

Page 16: Exchange Ma Pi

message.Notification.ItemsElementName[

count].ToString(),

mailEvent != null ?

mailEvent.TimeStamp.ToString(

"MM/dd/yyyy h:mm:ss tt") : ""));

count++;

}

3. Navigate to TODO: 5.4.9.

4. Add the following code after the TODO: 5.4.9 comment. This sets the subscription status to

OK, so the subscription will be continued by the Exchange Server.

C#

response = new SendNotificationResponse(

new SendNotificationResultType

{

SubscriptionStatus = SubscriptionStatusType.OK

});

5. Go to Debug >> Start Without Debugging or [Ctrl]+[F5] to start the application.

6. The console will display the subscription Id.

7. Switch to the secondary lab user’s session and open Microsoft Outlook.

8. Send an email to the primary lab user Id.

9. Return to the primary lab user’s session.

10. Verify that the NewMailEvent is recorded in the console.

Page 17: Exchange Ma Pi

11. Open Outlook and navigate to the Calendar.

12. Create an appointment for later in the day.

13. Verify that the CreatedEvent is recorded in the console.

14. Close the application.

Summary

In this lab, you used the EWS Managed API to build simple applications that leverage Exchange 2010

data and business logic. You saw how easy it is to get started with the EWS Managed API by showing the

simplicity of connecting to the correct Exchange CAS server, working with mailbox items, finding mailbox

items, and impersonating an Exchange user. You also learned how to attach metadata to mailbox items

using Extended Properties and how to search for mailbox items with a given Extended Property. You

used the Exchange Free-Busy Service to search for available meeting times for a set of users. Finally, you

saw how to subscribe to push notifications on the Exchange Server and listen for them using a WCF

service.