Tuesday, November 17, 2015

Finding the TimeZone being used in a Mailbox using EWS

If you ever have the need to create a number of events in user mailbox's from a central application or Script where the target Mailboxes span across different time zones then finding each target Mailbox's timezone is a critical thing. In this post I'm going to outline a few different methods of getting the TimeZone using EWS.

If you have access to the Exchange Management Shell cmdlet's to find the users configured timezone you can use either the Get-MailboxCalendarConfiguration or Get-MailboxRegionalConfiguration cmdlets which show you the timezone settings of a Mailbox from the WorkHours configuration of that mailbox. The object in the Mailbox that the information is read from/stored in is the IPM.Configuration.WorkHours FAI (Folder Assoicated Items) object in the Calendar Folder of the Mailbox. So if you want to access the TimeZone setting in Mailbox just using EWS you need to Bind to this UserConfiguration object (FAI object) and then parse the TimeZone Settings out of the WorkHours configuration XML document(which is documented in https://msdn.microsoft.com/en-us/library/ee157798(v=exchg.80).aspx) eg in Powershell something like the following should work okay

function GetWorkHoursTimeZone
{
    param( 
     [Parameter(Position=0, Mandatory=$true)] [String]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [Microsoft.Exchange.WebServices.Data.ExchangeService]$service
    )
 Begin
 {
   # Bind to the Calendar Folder
   $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar,$MailboxName)   
   $Calendar = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
   $sfFolderSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, "IPM.Configuration.WorkHours") 
   #Define ItemView to retrive just 1000 Items    
   $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1) 
   $ivItemView.Traversal = [Microsoft.Exchange.WebServices.Data.ItemTraversal]::Associated
   $fiItems = $service.FindItems($Calendar.Id,$sfFolderSearchFilter,$ivItemView) 
   if($fiItems.Items.Count -eq 1)
   {
    $UsrConfig = [Microsoft.Exchange.WebServices.Data.UserConfiguration]::Bind($service, "WorkHours", $Calendar.Id, [Microsoft.Exchange.WebServices.Data.UserConfigurationProperties]::All)  
    [XML]$WorkHoursXMLString = [System.Text.Encoding]::UTF8.GetString($UsrConfig.XmlData) 
    $returnVal = $WorkHoursXMLString.Root.WorkHoursVersion1.TimeZone.Name
    write-host ("Parsed TimeZone : " + $returnVal)
    Write-Output $returnVal
   }
   else
   {
    write-host ("No Workhours Object in Mailbox")
    Write-Output $null
   }
 }
}

 The other place in an Exchange Malbox where TimeZone information is held is in the OWA Configuration. This is set when a user logs onto to OWA the first time and then selects the timezone, the configuration is then stored in another FAI (in a Roaming Dictionary)with an ItemClass of IPM.Configuration.OWA.UserOptions in the NON_IPM root of the mailbox. Eg the following can be used to access this setting using EWS

function GetOWATimeZone{
    param( 
     [Parameter(Position=0, Mandatory=$true)] [String]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [Microsoft.Exchange.WebServices.Data.ExchangeService]$service
    )
 Begin
 {
   # Bind to the RootFolder Folder
   $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$MailboxName)   
   $RootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
   $sfFolderSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, "IPM.Configuration.OWA.UserOptions") 
   #Define ItemView to retrive just 1000 Items    
   $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1) 
   $ivItemView.Traversal = [Microsoft.Exchange.WebServices.Data.ItemTraversal]::Associated
   $fiItems = $service.FindItems($RootFolder.Id,$sfFolderSearchFilter,$ivItemView) 
   if($fiItems.Items.Count -eq 1)
   {
    $UsrConfig = [Microsoft.Exchange.WebServices.Data.UserConfiguration]::Bind($service, "OWA.UserOptions", $RootFolder.Id, [Microsoft.Exchange.WebServices.Data.UserConfigurationProperties]::All)  
    if($UsrConfig.Dictionary.ContainsKey("timezone"))
    {
     $returnVal = $UsrConfig.Dictionary["timezone"]
     write-host ("OWA TimeZone : " + $returnVal)
     Write-Output $returnVal
    }
    else
    {
     write-host ("TimeZone not set")
     Write-Output $null
    }
    
    
   }
   else
   {
    write-host ("No Workhours OWAConfig for Mailbox")
    Write-Output $null
   }
 }
}

If you tried both of these locations and still can't find the TimeZone (or your get a conflicting result) the last method you could try is to enumerate the last X number of appointments that where created by the user in the calendar (either a meeting they organized or a non meeting) and then enumerate the timezone used on those objects. The following is a sample of using the Calendar Appointments to work out the timezone of the user (It should return the most commonly used timezone base on the last 150 Calendar items).

function GetTimeZoneFromCalendarEvents{
    param( 
  [Parameter(Position=0, Mandatory=$true)] [String]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [Microsoft.Exchange.WebServices.Data.ExchangeService]$service
    )
 Begin
 {
  $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar,$MailboxName)   
  $Calendar = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
  $tzList = [TimeZoneInfo]::GetSystemTimeZones()
  $AppointmentStateFlags = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Appointment,0x8217,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);  
  $ResponseStatus = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Appointment,0x8218,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);  
  $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(150)  
  $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)  
  $psPropset.Add($AppointmentStateFlags)
  $psPropset.Add($ResponseStatus)
  $ivItemView.PropertySet = $psPropset
  $fiItems = $service.FindItems($Calendar.Id,$ivItemView)
  $tzCount = @{}
  if($fiItems.Items.Count -gt 0){
   foreach($Item in $fiItems.Items){
    $AppointmentStateFlagsVal = $null
    [Void]$Item.TryGetProperty($AppointmentStateFlags,[ref]$AppointmentStateFlagsVal)
    $ResponseStatusVal = $null
    [Void]$Item.TryGetProperty($ResponseStatus,[ref]$ResponseStatusVal)
    if($ResponseStatusVal -eq "Organizer" -bor $AppointmentStateFlagsVal -eq 0)
    {
     if($tzCount.ContainsKey($Item.TimeZone))
     {
      $tzCount[$Item.TimeZone]++
     }
     else
     {
      $tzCount.Add($Item.TimeZone,1)
     }
    }
   }    
  }
  $returnVal = $null
  if($tzCount.Count -gt 0){
   $fav = ""
   $tzCount.GetEnumerator() | sort -Property Value -Descending | foreach-object {
      if($fav -eq "")
      {
         $fav = $_.Key
      }
   }
    foreach($tz in $tzList)
   {
    if($tz.DisplayName -eq $fav)
    {
     $returnVal = $tz.Id
    }
   }
  }
  Write-Host ("TimeZone From Calendar Appointments : " + $returnVal)
  Write-Output $returnVal
 }
}

I've included all of these functions in a module that I've posted on GitHub here