Adicionar compromissos usando a representação do ExchangeAdd appointments by using Exchange impersonation

Saiba como usar a representação com a API gerenciada do EWS ou o EWS no Exchange para adicionar compromissos aos calendários dos usuários.Learn how to use impersonation with the EWS Managed API or EWS in Exchange to add appointments to users' calendars.

Você pode criar um aplicativo de serviço que insere compromissos diretamente em um calendário do Exchange usando uma conta de serviço que tenha a função ApplicationImpersonation habilitada.You can create a service application that inserts appointments directly into an Exchange calendar by using a service account that has the ApplicationImpersonation role enabled. Quando você usa a representação, o aplicativo está agindo como o usuário; é como se o usuário adicionasse o compromisso ao calendário usando um cliente como o Outlook.When you use impersonation, the application is acting as the user; it's as if the user added the appointment to the calendar by using a client such as Outlook.

Quando estiver usando a representação, tenha em mente o seguinte:When you are using impersonation, keep in mind the following:

  • O objeto ExchangeService deve estar associado à conta de serviço.Your ExchangeService object must be bound to the service account. Você pode usar o mesmo objeto ExchangeService para representar várias contas alterando a propriedade ImpersonatedUserId para cada conta que deseja representar.You can use the same ExchangeService object to impersonate multiple accounts by changing the ImpersonatedUserId property for each account that you want to impersonate.

  • Qualquer item que você salva em uma conta representada pode ser usado apenas uma vez.Any item that you save to an impersonated account can only be used once. Se você deseja salvar o mesmo compromisso em várias contas, por exemplo, você precisa criar um objeto de compromisso para cada conta.If you want to save the same appointment in multiple accounts, for example, you have to create an Appointment object for each account.

Pré-requisitosPrerequisites

Seu aplicativo precisa de uma conta para usar para se conectar ao servidor do Exchange antes de poder usar a representação.Your application needs an account to use to connect to the Exchange server before it can use impersonation. Sugerimos que você use uma conta de serviço para o aplicativo que recebeu a função de representação de aplicativo para as contas que ele acessará.We suggest that you use a service account for the application that has been granted the Application Impersonation role for the accounts that it will be accessing. Para obter mais informações, consulte Configure ImpersonationFor more information, see Configure impersonation

Adicionar compromissos usando representação com a API gerenciada do EWSAdd appointments by using impersonation with the EWS Managed API

O exemplo a seguir adiciona um compromisso ou reunião ao calendário de uma ou mais contas do Exchange.The following example adds an appointment or meeting to the calendar of one or more Exchange accounts. O método usa três parâmetros.The method takes three parameters.

  • serviço — um objeto ExchangeService associado à conta do aplicativo de serviço no servidor Exchange.service — An ExchangeService object bound to the service application's account on the Exchange server.

  • EmailAddresses — um objeto System. List contendo uma lista de cadeias de caracteres de endereços de email SMTP.emailAddresses — A System.List object containing a list of SMTP email address strings.

  • Factory — um objeto que implementa a interface IAppointmentFactory .factory — An object that implements the IAppointmentFactory interface. Essa interface tem um método, getcompromisso que recebe um objeto ExchangeService como um parâmetro e retorna um objeto compromisso .This interface has one method, GetAppointment that takes an ExchangeService object as a parameter and returns an Appointment object. A interface IAppointmentFactory é definida IAppointmentFactory interface.The IAppointmentFactory interface is defined IAppointmentFactory interface.

private static void CreateAppointments(ExchangeService service, List<string> emailAddresses, IAppointmentFactory factory)
{
  // Loop through the list of email addresses to add the appointment.
  foreach (var emailAddress in emailAddresses)
  {
    Console.WriteLine(string.Format("  Placing appointment in calendar for {0}.", emailAddress));
    // Set the email address of the account to get the appointment.
    service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, emailAddress);
    // Get the appointment to add.
    Appointment appointment = factory.GetAppointment(service);
    // Save the appointment.
    try
    {
      if (appointment.RequiredAttendees.Count > 0)
      {
        // The appointment has attendees so send them the meeting request.
        appointment.Save(SendInvitationsMode.SendToAllAndSaveCopy);
      }
      else
      {
        // The appointment does not have attendees, so just save to calendar.
        appointment.Save(SendInvitationsMode.SendToNone);
      }
    }
    catch (ServiceResponseException ex)
    {
      Console.WriteLine(string.Format("Could not create appointment for {0}", emailAddress));
      Console.WriteLine(ex.Message);
    }
  }
}

Ao salvar o compromisso, o código verifica para determinar se algum participante foi adicionado à propriedade RequiredAttendees .When saving the appointment, the code checks to determine whether any attendees have been added to the RequiredAttendees property. Se houver, o método de compromisso. Save é chamado com o valor de enumeração SendToAllAndSaveCopy para que os participantes recebam solicitações de reunião; caso contrário, o método de compromisso. Save é chamado com o valor de enumeração SendToNone para que o compromisso seja salvo no calendário do usuário representado com a propriedade compromisso. issatisfaçing definida como false.If they have, the Appointment.Save method is called with the SendToAllAndSaveCopy enumeration value so that the attendees receive meeting requests; otherwise, the Appointment.Save method is called with the SendToNone enumeration value so that the appointment is saved into the impersonated user's calendar with the Appointment.IsMeeting property set to false.

Interface IAppointmentFactoryIAppointmentFactory interface

Como você precisa de um novo objeto de compromisso sempre que quiser salvar um compromisso no calendário de um usuário representado, a interface IAppointmentFactory abstrai o objeto usado para preencher cada objeto de compromisso .Because you need a new Appointment object each time that you want to save an appointment on an impersonated user's calendar, the IAppointmentFactory interface abstracts the object used to populate each Appointment object. Esta versão é uma interface simples que contém apenas um método, getcompromisso, que usa um objeto ExchangeService como um parâmetro e retorna um novo objeto compromisso associado a esse objeto ExchangeService .This version is a simple interface that contains only one method, GetAppointment, that takes an ExchangeService object as a parameter and returns a new Appointment object bound to that ExchangeService object.

interface IAppointmentFactory
{
  Appointment GetAppointment(ExchangeService service);
}

O exemplo de classe AppointmentFactory a seguir mostra uma implementação da interface IAppointmentFactory que retorna um compromisso simples que ocorre três dias a partir de agora.The following AppointmentFactory class example shows an implementation of the IAppointmentFactory interface that returns a simple appointment that occurs three days from now. Se você remover o comentário da appointment.RequiredAttendees.Add linha, o método getcompromisso retornará uma reunião e o endereço de email especificado nessa linha receberá uma solicitação de reunião com o usuário representado listado como organizador.If you uncomment the appointment.RequiredAttendees.Add line, the GetAppointment method will return a meeting and the email address specified in that line will receive a meeting request with the impersonated user listed as the organizer.

class AppointmentFactory : IAppointmentFactory
{
  public Appointment GetAppointment(ExchangeService service)
  {
    // First create the appointment to add.
    Appointment appointment = new Appointment(service);
    // Set the properties on the appointment.
    appointment.Subject = "Tennis lesson";
    appointment.Body = "Focus on backhand this week.";
    appointment.Start = DateTime.Now.AddDays(3);
    appointment.End = appointment.Start.AddHours(1);
    appointment.Location = "Tennis club";
    // appointment.RequiredAttendees.Add(new Attendee("sonyaf@contoso1000.onmicrosoft.com"));
    return appointment;
  }
}

Adicionar compromissos usando representação com EWSAdd appointments by using impersonation with EWS

O EWS permite que o aplicativo use a representação para adicionar itens a um calendário em nome do proprietário do calendário.EWS enables you application to use impersonation to add items to a calendar on behalf the calendar's owner. Este exemplo mostra como usar a operação CreateItem para adicionar um compromisso ao calendário de uma conta representada.This example shows how to use the CreateItem operation to add an appointment to the calendar of an impersonated account.

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:m="https://schemas.microsoft.com/exchange/services/2006/messages" 
       xmlns:t="https://schemas.microsoft.com/exchange/services/2006/types" 
       xmlns:soap="https://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <t:RequestServerVersion Version="Exchange2013" />
    <t:TimeZoneContext>
      <t:TimeZoneDefinition Id="Pacific Standard Time" />
    </t:TimeZoneContext>
    <t:ExchangeImpersonation>
      <t:ConnectingSID>
        <t:SmtpAddress>alfred@contoso.com</t:SmtpAddress>
      </t:ConnectingSID>
    </t:ExchangeImpersonation>
  </soap:Header>
  <soap:Body>
    <m:CreateItem SendMeetingInvitations="SendToNone">
      <m:Items>
        <t:CalendarItem>
          <t:Subject>Tennis lesson</t:Subject>
          <t:Body BodyType="HTML">Focus on backhand this week.</t:Body>
          <t:ReminderDueBy>2013-09-19T14:37:10.732-07:00</t:ReminderDueBy>
          <t:Start>2013-09-21T19:00:00.000Z</t:Start>
          <t:End>2013-09-21T20:00:00.000Z</t:End>
          <t:Location>Tennis club</t:Location>
          <t:MeetingTimeZone TimeZoneName="Pacific Standard Time" />
        </t:CalendarItem>
      </m:Items>
    </m:CreateItem>
  </soap:Body>
</soap:Envelope>

Observe que, além da adição do elemento ExchangeImpersonation no cabeçalho SOAP, para especificar a conta que estamos representando, esta é a mesma solicitação XML usada para criar um compromisso sem usar representação.Note that other than the addition of the ExchangeImpersonation element in the SOAP header to specify the account that we are impersonating, this is the same XML request used to create an appointment without using impersonation.

O exemplo a seguir mostra a resposta XML retornada pela operação CreateItem .The following example shows the response XML that is returned by the CreateItem operation.

Observação

Os atributos ItemId e ChangeKey são reduzidos para facilitar a leitura.The ItemId and ChangeKey attributes are shortened for readability.

<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="https://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <h:ServerVersionInfo MajorVersion="15" MinorVersion="0" MajorBuildNumber="775" MinorBuildNumber="7" Version="V2_4" 
 xmlns:h="https://schemas.microsoft.com/exchange/services/2006/types" 
 xmlns="https://schemas.microsoft.com/exchange/services/2006/types" 
 xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
  </s:Header>
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <m:CreateItemResponse xmlns:m="https://schemas.microsoft.com/exchange/services/2006/messages" 
  xmlns:t="https://schemas.microsoft.com/exchange/services/2006/types">
      <m:ResponseMessages>
        <m:CreateItemResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:Items>
            <t:CalendarItem>
              <t:ItemId Id="AAMkA" ChangeKey="DwAAA" />
            </t:CalendarItem>
          </m:Items>
        </m:CreateItemResponseMessage>
      </m:ResponseMessages>
    </m:CreateItemResponse>
  </s:Body>
</s:Envelope>

Novamente, esse é o mesmo XML que é retornado quando você usa a operação CreateItem sem usar representação.Again, this is the same XML that is returned when you use the CreateItem operation without using impersonation.

Confira tambémSee also