Thursday, October 31, 2013

Creating a Shared Calendar Shortcut (WunderBar Link) with EWS and Powershell

Shared Calendar Shortcuts eg



are an Outlook and OWA  feature that can be handy to automate if you need to deploy a number of these to new (or existing) mailboxes and you don't want to go through the invitation/accept procedure or manually adding each shortcut.

While there are no supported operations in EWS for creating these type of objects, it can be achieved by setting the Extended MAPI properties that constitute the shortcut. The downside of this is that it wouldn't ever be considered supported if it all goes horribly wrong. The properties involved in the shortcut are documented in the following protocol document http://msdn.microsoft.com/en-us/library/ee157359(v=exchg.80).aspx.

For a couple of these properties the values you need to get can't be obtained directly in EWS so some others tricks are needed.

The PidTagWlinkAddressBookEID property contains the MAPI address Book EntryId for the shared Calendar your connecting to. The Address Book EntryID format is documented here http://msdn.microsoft.com/en-us/library/ee160588%28v=exchg.80%29.aspx so to construct this in EWS you need to get the LegacyExchangeDN from AutoDiscover and then appended the ProviderUID,Flag and Type information which for a normal user will be the same. (Note if you are trying to connect to an object other then a user mailbox.

The PidTagWlinkAddressBookStoreEID proeprty contains the MAPI StoreEntryID of the users where your creating the ShortCut. While you can get this property in EWS the value you get isn't correct because EWS uses different wrapper and providerID values. So instead using the format documented in http://msdn.microsoft.com/en-us/library/ee203516%28v=exchg.80%29.aspx you can construct this which involves getting the LegacyExchangeDN and the ServerName for Autodiscover and then building the identifier.

The other properties are pretty static for shared calendars.

The ShortCuts them selves are saved in a Non_IPM_Subtree folder called common views

(Special thanks also to Neil Doody for helping with property definitions in this post and script)

So the following script takes two commandline parameter the first is the Mailbox where you want the shortcut to be created and the second is the Mailbox which has the Calendar you want the shortcut to point to so you would run it like

./createWBarCal.ps1 user@domain.com target@domain.com

 The script will check the CommonViews folder to see if a SharedFolder shortcut already exists for the target Mailbox AddressId and FolderType and if no ShortCut exists and it will attempt to create one.

As i mentioned before as this script is completely unsupported and for the most part untested and should only be considered safe for testing in a development\test environment. It also assume you have Autodiscover working if not your this isn't going to work well.

 I've put a download of the script here the code itself looks like

  1. ## Get the Mailbox to Access from the 1st commandline argument  
  2. $TargetCalendarMailbox = $args[1]  
  3. $MailboxName = $args[0]  
  4.   
  5. ## Load Managed API dll    
  6. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"    
  7.     
  8. ## Set Exchange Version    
  9. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2    
  10.     
  11. ## Create Exchange Service Object    
  12. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  13.     
  14. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  15.     
  16. #Credentials Option 1 using UPN for the windows Account    
  17. $psCred = Get-Credential    
  18. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  19. $service.Credentials = $creds        
  20.     
  21. #Credentials Option 2    
  22. #service.UseDefaultCredentials = $true    
  23.     
  24. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  25.     
  26. ## Code From http://poshcode.org/624  
  27. ## Create a compilation environment  
  28. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  29. $Compiler=$Provider.CreateCompiler()  
  30. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  31. $Params.GenerateExecutable=$False  
  32. $Params.GenerateInMemory=$True  
  33. $Params.IncludeDebugInformation=$False  
  34. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  35.   
  36. $TASource=@' 
  37.   namespace Local.ToolkitExtensions.Net.CertificatePolicy{ 
  38.     public class TrustAll : System.Net.ICertificatePolicy { 
  39.       public TrustAll() {  
  40.       } 
  41.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  42.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  43.         System.Net.WebRequest req, int problem) { 
  44.         return true; 
  45.       } 
  46.     } 
  47.   } 
  48. '@   
  49. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  50. $TAAssembly=$TAResults.CompiledAssembly  
  51.   
  52. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  53. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  54. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  55.   
  56. ## end code from http://poshcode.org/624  
  57.     
  58. ## Set the URL of the CAS (Client Access Server) to use two options are availbe to use Autodiscover to find the CAS URL or Hardcode the CAS to use    
  59.     
  60. #CAS URL Option 1 Autodiscover    
  61. $service.AutodiscoverUrl($MailboxName,{$true})    
  62. "Using CAS Server : " + $Service.url     
  63.      
  64. #CAS URL Option 2 Hardcoded    
  65.     
  66. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  67. #$service.Url = $uri      
  68.     
  69. ## Optional section for Exchange Impersonation    
  70.     
  71. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  72.   
  73. function GetAutoDiscoverSettings{  
  74.     param (  
  75.             $adEmailAddress = "$( throw 'emailaddress is a mandatory Parameter' )",  
  76.             $Credentials = "$( throw 'Credentials is a mandatory Parameter' )"  
  77.           )  
  78.     process{  
  79.         $adService = New-Object Microsoft.Exchange.WebServices.AutoDiscover.AutodiscoverService($ExchangeVersion);  
  80.         $adService.Credentials = $Credentials  
  81.         $adService.EnableScpLookup = $false;  
  82.         $adService.RedirectionUrlValidationCallback = {$true}  
  83.         $UserSettings = new-object Microsoft.Exchange.WebServices.Autodiscover.UserSettingName[] 3  
  84.         $UserSettings[0] = [Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::UserDN  
  85.         $UserSettings[1] = [Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::InternalRpcClientServer  
  86.         $UserSettings[2] = [Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::UserDisplayName  
  87.         $adResponse = $adService.GetUserSettings($adEmailAddress , $UserSettings);  
  88.         return $adResponse  
  89.     }  
  90. }  
  91. function GetAddressBookId{  
  92.     param (  
  93.             $AutoDiscoverSettings = "$( throw 'AutoDiscoverSettings is a mandatory Parameter' )"  
  94.           )  
  95.     process{  
  96.         $userdnString = $AutoDiscoverSettings.Settings[[Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::UserDN]  
  97.         $userdnHexChar = $userdnString.ToCharArray();  
  98.         foreach ($element in $userdnHexChar) {$userdnStringHex = $userdnStringHex + [System.String]::Format("{0:X}", [System.Convert]::ToUInt32($element))}  
  99.         $Provider = "00000000DCA740C8C042101AB4B908002B2FE1820100000000000000"  
  100.         $userdnStringHex = $Provider + $userdnStringHex + "00"  
  101.         return $userdnStringHex  
  102.     }  
  103. }  
  104. function GetStoreId{  
  105.     param (  
  106.             $AutoDiscoverSettings = "$( throw 'AutoDiscoverSettings is a mandatory Parameter' )"  
  107.           )  
  108.     process{  
  109.         $userdnString = $AutoDiscoverSettings.Settings[[Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::UserDN]  
  110.         $userdnHexChar = $userdnString.ToCharArray();  
  111.         foreach ($element in $userdnHexChar) {$userdnStringHex = $userdnStringHex + [System.String]::Format("{0:X}", [System.Convert]::ToUInt32($element))}   
  112.         $serverNameString = $AutoDiscoverSettings.Settings[[Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::InternalRpcClientServer]  
  113.         $serverNameHexChar = $serverNameString.ToCharArray();  
  114.         foreach ($element in $serverNameHexChar) {$serverNameStringHex = $serverNameStringHex + [System.String]::Format("{0:X}", [System.Convert]::ToUInt32($element))}  
  115.         $flags = "00000000"  
  116.         $ProviderUID = "38A1BB1005E5101AA1BB08002B2A56C2"  
  117.         $versionFlag = "0000"  
  118.         $DLLFileName = "454D534D44422E444C4C00000000"  
  119.         $WrappedFlags = "00000000"  
  120.         $WrappedProviderUID = "1B55FA20AA6611CD9BC800AA002FC45A"  
  121.         $WrappedType = "0C000000"  
  122.         $StoredIdStringHex = $flags + $ProviderUID + $versionFlag + $DLLFileName + $WrappedFlags + $WrappedProviderUID + $WrappedType + $serverNameStringHex + "00" + $userdnStringHex + "00"  
  123.         return $StoredIdStringHex  
  124.     }  
  125. }  
  126.   
  127.   
  128. function hex2binarray($hexString){  
  129.     $i = 0  
  130.     [byte[]]$binarray = @()  
  131.     while($i -le $hexString.length - 2){  
  132.         $strHexBit = ($hexString.substring($i,2))  
  133.         $binarray += [byte]([Convert]::ToInt32($strHexBit,16))  
  134.         $i = $i + 2  
  135.     }  
  136.     return ,$binarray  
  137. }  
  138. function ConvertId($EWSid){      
  139.     $aiItem = New-Object Microsoft.Exchange.WebServices.Data.AlternateId        
  140.     $aiItem.Mailbox = $MailboxName        
  141.     $aiItem.UniqueId = $EWSid     
  142.     $aiItem.Format = [Microsoft.Exchange.WebServices.Data.IdFormat]::EWSId;        
  143.     return $service.ConvertId($aiItem, [Microsoft.Exchange.WebServices.Data.IdFormat]::StoreId)       
  144. }   
  145.   
  146. #PropDefs   
  147. $pidTagStoreEntryId = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(4091, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  148. $PidTagNormalizedSubject = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x0E1D,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);   
  149. $PidTagWlinkType = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6849, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer)  
  150. $PidTagWlinkFlags = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x684A, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer)  
  151. $PidTagWlinkOrdinal = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x684B, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  152. $PidTagWlinkFolderType = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x684F, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  153. $PidTagWlinkSection = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6852, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer)  
  154. $PidTagWlinkGroupHeaderID = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6842, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  155. $PidTagWlinkSaveStamp = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6847, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer)  
  156. $PidTagWlinkGroupName = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6851, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String)  
  157. $PidTagWlinkStoreEntryId = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x684E, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  158. $PidTagWlinkGroupClsid = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6850, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  159. $PidTagWlinkEntryId = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x684C, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  160. $PidTagWlinkRecordKey = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x684D, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  161. $PidTagWlinkCalendarColor = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6853, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer)  
  162. $PidTagWlinkAddressBookEID = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6854,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  163. $PidTagWlinkROGroupType = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6892,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer)  
  164. $PidTagWlinkAddressBookStoreEID = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6891,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  165.   
  166.   
  167. #Get the TargetUsers Calendar  
  168. # Bind to the Calendar Folder  
  169. $fldPropset = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  170. $fldPropset.Add($pidTagStoreEntryId);  
  171. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar,$TargetCalendarMailbox)     
  172. $TargetCalendar = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid,$fldPropset)  
  173. #Check for existing ShortCut for TargetMailbox  
  174. #Get AddressBook Id for TargetUser  
  175. Write-Host ("Getting Autodiscover Settings Target")  
  176. Write-Host ("Getting Autodiscover Settings Mailbox")  
  177. $adset = GetAutoDiscoverSettings -adEmailAddress $MailboxName -Credentials $creds  
  178. $storeID = ""  
  179. if($adset -is [Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverResponse]){  
  180.     Write-Host ("Get StoreId")  
  181.     $storeID = GetStoreId -AutoDiscoverSettings $adset  
  182. }  
  183. $adset = $null  
  184. $abTargetABEntryId = ""  
  185. $adset = GetAutoDiscoverSettings -adEmailAddress $TargetCalendarMailbox -Credentials $creds  
  186. if($adset -is [Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverResponse]){  
  187.     Write-Host ("Get AB Id")  
  188.     $abTargetABEntryId = GetAddressBookId -AutoDiscoverSettings $adset  
  189.     $SharedUserDisplayName =  $adset.Settings[[Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::UserDisplayName]  
  190. }  
  191. Write-Host ("Getting CommonVeiwFolder")  
  192. #Get CommonViewFolder  
  193. $folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$MailboxName)     
  194. $tfTargetFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)    
  195. $fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1)   
  196. $SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,"Common Views")   
  197. $findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView)   
  198. if ($findFolderResults.TotalCount -gt 0){   
  199.     $ExistingShortCut = $false  
  200.     $cvCommonViewsFolder = $findFolderResults.Folders[0]  
  201.     #Define ItemView to retrive just 1000 Items      
  202.     #Find Items that are unread  
  203.     $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  204.     $psPropset.add($PidTagWlinkAddressBookEID)  
  205.     $psPropset.add($PidTagWlinkFolderType)  
  206.     $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)     
  207.     $ivItemView.Traversal = [Microsoft.Exchange.WebServices.Data.ItemTraversal]::Associated  
  208.     $ivItemView.PropertySet = $psPropset  
  209.     $fiItems = $service.FindItems($cvCommonViewsFolder.Id,$ivItemView)      
  210.     foreach($Item in $fiItems.Items){  
  211.         $aeidVal = $null  
  212.         if($Item.TryGetProperty($PidTagWlinkAddressBookEID,[ref]$aeidVal)){  
  213.                 $fldType = $null  
  214.                 if($Item.TryGetProperty($PidTagWlinkFolderType,[ref]$fldType)){  
  215.                     if([System.BitConverter]::ToString($fldType).Replace("-","") -eq "0278060000000000C000000000000046"){  
  216.                         if([System.BitConverter]::ToString($aeidVal).Replace("-","") -eq $abTargetABEntryId){  
  217.                             $ExistingShortCut = $true  
  218.                             Write-Host "Found existing Shortcut"  
  219.                             ###$Item.Delete([Microsoft.Exchange.WebServices.Data.DeleteMode]::SoftDelete)  
  220.                         }  
  221.                     }  
  222.                 }  
  223.             }                               
  224.     }  
  225.     if($ExistingShortCut -eq $false){  
  226.         If($storeID.length -gt 5 -band $abTargetABEntryId.length -gt 5){  
  227.             $objWunderBarLink = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service    
  228.             $objWunderBarLink.Subject = $SharedUserDisplayName    
  229.             $objWunderBarLink.ItemClass = "IPM.Microsoft.WunderBar.Link"    
  230.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkAddressBookEID,(hex2binarray $abTargetABEntryId))    
  231.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkAddressBookStoreEID,(hex2binarray $storeID))    
  232.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkCalendarColor,-1)  
  233.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkFlags,0)  
  234.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkGroupName,"Shared Calendars")  
  235.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkFolderType,(hex2binarray "0278060000000000C000000000000046"))    
  236.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkGroupClsid,(hex2binarray "B9F0060000000000C000000000000046"))    
  237.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkROGroupType,-1)  
  238.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkSection,3)    
  239.             $objWunderBarLink.SetExtendedProperty($PidTagWlinkType,2)    
  240.             $objWunderBarLink.IsAssociated = $true  
  241.             $objWunderBarLink.Save($findFolderResults.Folders[0].Id)  
  242.             Write-Host ("ShortCut Created for - " + $SharedUserDisplayName)  
  243.         }  
  244.         else{  
  245.             Write-Host ("Error with Id's")  
  246.         }  
  247.     }  
  248. }  






7 comments:

Anonymous said...

Hi, great script, can I use that also to delete an ExchangeSyncData folder? I need to automate this step, so I can't use MFCMAPI for the delete. (approx 1000 users)
Thanks

Glen Scales said...

This script doesn't really have anything to do with ExchangeSyncData and you need to be careful there is also Active Directory information associated with ActiveSync data. You should use the Remove-ActiveSyncData cmdlet http://technet.microsoft.com/en-us/library/bb125032%28v=exchg.141%29.aspx to clean these out correctly

Neil Doody said...

Great work Glen, glad to see this published...I really think it could help people with planning for these kind of migrations where you're moving away from public folders. Just remember to plan to move the users before the resources...otherwise we can't manipulate the mailboxes that are still on a legacy (2003) exchange environment (speaking from a little experience).

We could possibly work to enhance this by adding shared contacts / etc...maybe for another time :)

Anonymous said...

I know, the devices, which are having a partnership are in the AD as well. I already took care about that, but I still need to delete the hidden folder...

BUT, I found a solution:
I use EWS to do that job, its a MS script for the Recovery Mailbox. Its connecting the user's mailbox with a privilleged account and parsing through and finds the Folders Display name. And then do a Soft- or Harddelete.
If somebody is interessting on the commands, just answer here.

Justin said...

Glen,
I've been looking over this, and working out how to customize for my customer - they have some interesting requirements.

One of their requirements that's bugging me is that they'd like to add regular Mail PF shortcuts in via EWS too. As near as I can tell, this requires some additional work (adding items and folders under "Shortcuts" in the NON_IPM_SUBTREE) apart from just creating the Wunderbar objects under "Common Views").

(For what it's worth, I tried adding just the entry under "Common Views" with MFCMAPI - I think OWA promptly deleted it as incorrect, but I might've typed something in incorrectly. Adding the items via Outlook (unfortunately 2013/64bit doesn't like AddToPFFavorites via script...), and then deleting the associated "Shortcuts" failed miserably too.

Not sure if you have a sample of such code to hand that I could leverage? I'm leaning towards there not being a solution via EWS - I might have to look into Redemption or similar.

Anyway - thanks for this script - useful!

Justin

Glen Scales said...

I've not seen the public folder short-cuts documented anywhere so i would say you would be better to stick with Redemption and AddToPFFavorites. If you could track all the property changes to items then you could do it with EWS but its a time-consuming process.

Cheers
Glen

Anonymous said...

I reversed engineered this into C# code and it works great.
What do you do if this works but it is not showing up in Outlook 2010 but does in Outlook web?