Friday, December 18, 2009

Using ADSI to find your CAS or Mailbox Role servers in VBS or PowerShell

While the Exchange Management Shell is a thing of wonder its not always available when your writing a script or piece of real code and you need to do something like finding your Exchange 2007/2010 CAS or Mailbox role servers. The good news is like most of the Exchange configuration information this is stored in Active directory and can be relatively easily queried using LDAP and ADSI.

The AD property that holds this information about what particular roles are installed on a Exchange server is the msExchCurrentServerRoles property. This property contain a number of bitwise flags that indicate which roles are installed as per http://technet.microsoft.com/en-us/library/bb123496(EXCHG.80).aspx .

Server role Role value

Mailbox role 2
Client Access role (CAS) 4
Unified Messaging role 16
Hub Transport role 32
Edge Transport role 64

So to query these in ADSI we need to use a Bitwise filter as per http://support.microsoft.com/kb/269181

So the LDAP filter to return all the server with the mailbox role would be

(msExchCurrentServerRoles:1.2.840.113556.1.4.803:=2)

for CAS Servers you would use

msExchCurrentServerRoles:1.2.840.113556.1.4.803:=4)

To put this into a larger script in VBS

Set Conn = CreateObject("ADODB.Connection")
Set com = CreateObject("ADODB.Command")
Set iAdRootDSE = GetObject("LDAP://RootDSE")
strNameingContext = iAdRootDSE.Get("configurationNamingContext")
Conn.Provider = "ADsDSOObject"
Conn.Open "ADs Provider"
svcQuery = "<LDAP://CN=Microsoft Exchange,CN=Services," & strNameingContext & ">;(&(&(objectCategory=msExchExchangeServer)" _
& "(msExchCurrentServerRoles:1.2.840.113556.1.4.803:=4)));cn,name,serialNumber,distinguishedName,legacyExchangeDN;subtree"
com.ActiveConnection = Conn
com.CommandText = svcQuery
Set rs = com.Execute
While Not rs.EOF
wscript.echo rs.Fields("cn")
rs.MoveNext
Wend


In powershell something like this should work

$root = [ADSI]'LDAP://RootDSE'
$cfConfigRootpath = "LDAP://" + $root.ConfigurationNamingContext.tostring()
$configRoot = [ADSI]$cfConfigRootpath
$searcher = new-object System.DirectoryServices.DirectorySearcher($configRoot)
$searcher.Filter = '(&(&(objectCategory=msExchExchangeServer)(msExchCurrentServerRoles:1.2.840.113556.1.4.803:=4)))'
[VOID]$searcher.PropertiesToLoad.Add("cn")
$searchres = $searcher.FindAll()
foreach ($res in $searchres){
$srvOjb = $res.Properties
$srvOjb.cn
}

Saturday, December 12, 2009

Changing OWA configuration setting with EWS in Exchange 2010

The ability to change and customise the default configuration of OWA is an often sort out and in previous versions of Exchange hard to achieve task. Especially for those with Large Exchange Orgs and standardised training or custom security requirements where the default settings come into conflict with other policies. Underlying a lot of OWA configuration settings are stored in FAI items (folder associated items) in a users mailbox using the Configuration Information Protocol Specification documented in http://msdn.microsoft.com/en-us/library/cc463899(EXCHG.80).aspx.

Along with the ability to access FAI items which was previously not possible in Exchange 2007 using EWS, Exchange 2010 also introduces a new UserConfiguration Operation in EWS that provides some Typed objects the makes dealing with configuration objects a lot easier and safer for those that wish to do so. (I still wouldn't guarantee the support response you would get if you do use these Operations and stuff your Exchange Org completely this is a risk you should understand before undertaking such an endeavor). What having these strong objects to use if your using Proxy code or the EWS Managed API means is that a task that may have taken a lot effort and reverse engineering in the past to achieve is really now something you can do fairly easy with a couple of lines of code or script.

The User configuration FAI items can be located in different folders in a Mailbox the one im going to focus on in this post is the OWA.UserOptions object which contain things such as the readingpane setting, OWA signiture and other general settings. The message itself has a message class of IPM.Configuration.OWA.UserOptions if you looked at it with a Mapi editor and its located in the Non_IPM_Subtree (ed Note since the removal of Dav in Exchange 2010 is this still the right terminology??).

This brings up an important point for anybody trying to modify these type of objects one tool you will find invaluable is a Mapi editory like the MFCMapi or OutlookSpy. Another useful tool is now the EWS editor these two tools will make doing this type of thing a lot eaiser as they can allow you to browse and see the current values of properties on items. You should also read the the protocol document i linked above and have an understanding of the datatypes involved with the properties your setting and make sure you adhere to this. Eg dont use a String where a Interger is expected etc.

For this post im also using the EWS Managed API which saves time and sanity when writing EWS code.

Lets get down to the code the first thing you need to do is get the FolderID for the Non_Ipm_Subtee, to do this you Bind to the Root folder and use the parentFolderID property

Folder Root = Folder.Bind(service, WellKnownFolderName.Root);

Next you use the UserConfiguration objects bind method and pass the following parameters in

UserConfiguration OWAConfig = UserConfiguration.Bind(service, "OWA.UserOptions", Root.ParentFolderId, UserConfigurationProperties.All);

Note that you take the MessageClass of the Item IPM.Configuration.OWA.UserOptions and drop the IPM.Configuration part.

This will then get the existing configuration object settings from this particular folder item which for this item will be returned as a dictionary collection. If you want to enum through all the properties you can do the following

IDictionaryEnumerator ConfigEnum = (IDictionaryEnumerator)OWAConfig.Dictionary.GetEnumerator();
while (ConfigEnum.MoveNext()) {
Console.WriteLine("Key : " + ConfigEnum.Key);
Console.WriteLine("Value : " + ConfigEnum.Value);
}


To Set a value it pretty simple eg

if(OWAConfig.Dictionary.ContainsKey("previewmarkasread")){
OWAConfig.Dictionary["previewmarkasread"] = 2;
}
else{
OWAConfig.Dictionary.Add("previewmarkasread", 2);
}
OWAConfig.Update();

This turns the Mark as Read off in the previewpane in OWA note that this is a Intager value.

To do this in Powershell script that you could feed with get-mailbox it would look like the following I've put a download of the code here

$MailboxName = "user@domain.com"

$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\1.0\Microsoft.Exchange.WebServices.dll"
[void][Reflection.Assembly]::LoadFile($dllpath)
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010)

$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
$aceuser = [ADSI]$sidbind

$service.AutodiscoverUrl($mailboxname)

$folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$MailboxName)
$Root = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
$OWAConfig = [Microsoft.Exchange.WebServices.Data.UserConfiguration]::Bind($service, "OWA.UserOptions", $Root.ParentFolderId, [Microsoft.Exchange.WebServices.Data.UserConfigurationProperties]::All)
if($OWAConfig.Dictionary.ContainsKey("previewmarkasread")){
$OWAConfig.Dictionary["previewmarkasread"] = 2 }
else{
$OWAConfig.Dictionary.Add("previewmarkasread", 2)
}
$OWAConfig.Update()
"Done"

Friday, December 04, 2009

Using Contact photo's in EWS in Exchange 2010

Contact photo's where a feature first introduced in Outlook 2003 but up until the release on Exchange 2010 not something you could use in EWS. This should not be confused with another new feature in Exchange 2010 which is the ability to upload a picture to the Gal (or the directory to be more precise) if your interested in finding out more about that check out Ilse post .

So the Contact photo's I'm talking about are those that are associated with contact Items in your mailbox. About 4 years ago i posted this script (which was rubbish) for doing this with CDO 1.2 importantly in the heady stile of 2005 i pointed out that when using contact photos you need to set some extended properties on the attachment. Now while you still can't do this with EWS :( in 2010 they have added the ability to set the properties of a contact photo(just wish they hadn't stopped there). Further the EWS Managed API actually makes the process of adding a contact photo quite easy.

So a very simple piece of code to add a contact photo in C# would look like


ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
service.AutodiscoverUrl("emailaddres@domain.com");
Folder Contacts = Folder.Bind(service, WellKnownFolderName.Contacts);
Contact cn1 = new Contact(service);
cn1.GivenName = "Fred";
cn1.Surname = "Bloggs";
cn1.EmailAddresses[EmailAddressKey.EmailAddress1] = "fblogs@domain.com";
cn1.Subject = "Fred Bloggs";
FileAttachment atattach = cn1.Attachments.AddFileAttachment("c:\\contactphoto.jpg");
atattach.IsContactPhoto = true;
cn1.Save();

For those looking for a Powershell version that you can put to work I've got one of those as well the following is a script that allows you to specify the emailaddress of the contact you want update and the photo you want to use. The script will then search for this conact in the mailboxes contact folder and upload the picture to it (if found). I've put a download of this script here the code itself looks like.

$MailboxName = "user@mbmailbox.com"
$emEmailAdddrestoFind = "fred@fred.com"
$cntPhotoFile = "c:\ck1.jpg"

$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\1.0\Microsoft.Exchange.WebServices.dll"
[void][Reflection.Assembly]::LoadFile($dllpath)
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010)

$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
$aceuser = [ADSI]$sidbind

$service.AutodiscoverUrl($mailboxname)

$folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Contacts,$MailboxName)
$ContactsFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
$Iview = new-object Microsoft.Exchange.WebServices.Data.ItemView(1000)
$SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.ContactSchema]::EmailAddress1,$emEmailAdddrestoFind)
$frContactResults = $ContactsFolder.FindItems($SfSearchFilter,$Iview)
foreach ($cnContacts in $frContactResults.Items){
$cnContacts.Subject
$atattach = $cnContacts.Attachments.AddFileAttachment($cntPhotoFile)
$atattach.IsContactPhoto = $true
$cnContacts.update([Microsoft.Exchange.WebServices.Data.ConflictResolutionMode]::AlwaysOverwrite)
}