Sunday, May 24, 2009

Mail Enabling a Public folder with the EWS Managed API and finding and changing the primary email address without using Exchange cmdlets

If your working with Public Folders in the EWS Managed API then you may want to mailenable a new or existing Public Folder without using EMS cmdlets. I described a method that you can use to mail enable Public folders using EWS a while ago here and this same method will work with a little bit of different code. Like the previous post you need to set the following 2 properties to mail enabled a folder.

PR_PUBLISH_IN_ADDRESS_BOOK = 0x3FE6000B
PR_PF_PROXY_REQUIRED = 0x671F000B

So if you want to mailenable an existing folder that you have the path for say its "firstlevel/secondlevel/newfolder" you will first need to have some code that will find the folder based on the path by doing a search. Then once you have the folder ID you can Bind to the folder and set those Mapi properties. Using a UpdateFolder operation was one of the harder operations in normal EWS proxy code but its now so much easier to do in the EWS Managed API.

Once you have set these properties a backgroup process will create the AD Proxy object for this public folder which will contain all the email address's assigned to this and any other folder specific setting such a limits etc. If you want to connect to this proxy object and change things like limits and email address you can use LDAP directly without using the EMS cmdlets. A little word or warning if you are going to be setting email addresses directly you should make sure you implement code that ensures you dont create duplicate email addresses. To find the ADProxy object you can get the AD GUID of the proxy object by retrieving the following property via EWS and then use this GUID value to access the AD object.

PR_PF_PROXY = 0x671D

This is a binary property which will be returned base64 encoded so you first need to decode this and the convert it to hex to use in a System.DirectoryServices.

So the code to MailEnable a folder using the EWS Managed API looks like

String fpfolderPath = "";
ExtendedPropertyDefinition PR_PF_PROXY = new ExtendedPropertyDefinition(0x671D, MapiPropertyType.Binary);
PropertySet PsPropertySet = new PropertySet(PR_PF_PROXY);
PsPropertySet.BasePropertySet = BasePropertySet.FirstClassProperties;
Folder PfRoot = Folder.Bind(service, WellKnownFolderName.PublicFoldersRoot,PsPropertySet);
String[] faFldArray = fpfolderPath.Split('/');
Folder tfTargetFolder = PfRoot;
for (int lint = 1; lint < fview =" new" searchfilter =" new" propertyset =" PsPropertySet;" ffresult =" service.FindFolders(tfTargetFolder.Id," totalcount ="=" tftargetfolder =" ffResult.Folders[0];" pr_publish_in_address_book =" new" pr_pf_proxy_required =" new">


To access the AD proxy object using the FolderID from the prevous piece of code


ExtendedPropertyDefinition PR_PF_PROXY = new ExtendedPropertyDefinition(0x671D, MapiPropertyType.Binary);
PropertySet PsPropertySet = new PropertySet(PR_PF_PROXY);
Folder meMailEnabledFolder = Folder.Bind(service, tfTargetFolder.Id, PsPropertySet);
String pfProxy = "";
tfTargetFolder.Update();
byte[] pfPro = Convert.FromBase64String(meMailEnabledFolder.ExtendedProperties[0].Value.ToString());
pfProxy = BitConverter.ToString(pfPro);
DirectoryEntry deDirEnt = new DirectoryEntry(("LDAP://<GUID=" + pfProxy.Replace("-", "") + ">"));
PropertyValueCollection proxyAddresses = deDirEnt.Properties["proxyAddresses"];
if (proxyAddresses != null)
{
for (int ipar = 0; ipar < proxyAddresses.Count; ipar++)
{
Console.WriteLine(proxyAddresses[ipar].ToString());
if (proxyAddresses[ipar].ToString().Contains("SMTP:"))
{
proxyAddresses[ipar] = "SMTP:address@domain.com.au";
}
}
}
deDirEnt.CommitChanges();

I've put a download of this code here

Friday, May 22, 2009

Acknowledging Appointment reminders with WebDAV

One thing that can be little tricky if your working in WebDAV is dealing with appointment reminders, especially when you have to deal with recurring appointments. If you dont use the right method its easy to break the recurrance of appointments. The best way of working something like this out is have a look at the way OWA does it and then just use the same xml. So basically what you end up with is firstly a method to acknowledge non-recurring appointment reminders by removing the reminderoffset property. And a method to acknowledge recurring appointment reminders by setting the remindernexttime property. I've put a download of this VBS script here the code looks like
eg

set req = Createobject("microsoft.xmlhttp")

CalendarURL = "https://servername/exchange/mailbox/calendar"
AppointmentURL = CalendarURL & "/appointment.eml"

If RecurringAppointment = false Then
xmlstr = "<?xml version=""1.0""?><a:propertyupdate xmlns:a=""DAV:""><a:remove><a:prop>" _
& "<d:reminderoffset xmlns:d=""urn:schemas:calendar:"" /></a:prop></a:remove>" _
& "<a:target><a:href>" & AppointmentURL & "</a:href></a:target></a:propertyupdate>"
else
xmlstr = "<?xml version=""1.0""?><a:propertyupdate xmlns:a=""DAV:""><a:set><a:prop>" _
& "<d:remindernexttime xmlns:d=""urn:schemas:calendar:"">4501-01-01T00:00:00.000Z</d:remindernexttime>" _
& "</a:prop></a:set><a:target><a:href>" & AppointmentURL & "</a:href></a:target></a:propertyupdate>"
End if

req.open "BPROPPATCH", CalendarURL, False
req.setRequestHeader "Content-Type", "text/xml;"
req.setRequestHeader "Translate", "f"
req.setRequestHeader "Content-Length:", Len(xmlstr)
req.send(xmlstr)
If (req.Status >= 200 And req.Status < 300) Then
Wscript.echo "Reminder Acknowledged"
else
Wscript.echo "Request Failed. Results = " & req.Status & ": " & req.statusText
End If

Saturday, May 09, 2009

Mailbox Size Summary reporting Gui for Exchange 2007

Picking up again on the topic i touched on in January about creating different summary reports of how size and resources are consummed within an Exchange enviroment he's a script that takes it in another direction (and dont we need one of those). A number of people have asked questions about how they can report on mailbox usage not just based on particular users but usage by particular OU or other User property eg Department,Office etc. An here's the script to do it

How it works


This script first combines 3 different Exchange cmdlets to build a displayable and redisplayble dataset that is stored in hashtable. The Get-User cmdlet is used to get all the user information and a number of properties such as the ExchangeGUID,MailboxSize and what OU a users is in is addded to the standard Get-User object and then the object is stored in a hashtable indexed by the Active Directory GUI. Because you can't link directly Get-User and Get-Mailboxstatistics directly without using Pipeline composition which will do a search for each user making this script a little to slow for enviroments with a large number of users. Get-Mailbox is used to create a hashtable that allows the linking of the information that is returned by the Get-User cmdlet and what is returned by the Get-Mailboxstatistics.

To build display elements all the properties from Get-User are added to the Dropdown for Groupby type. When this is selected it fires a function that causes the data stored in the results hashtable to be regrouped using the selected value which then rebuilds the data in the datatable which in tern refreshs what you see in the datagrid. To spice things up a bit I've added some extra functionality like being able to get the actally mailboxes that are being included in the grouping in a seperate datatable. Also the ability to export both grids to a csv file. The final things to give this script some visual spark by adding a few Google charts to add a visual dimension to the summariesed data

The result is a script that produces a lot of quite interesting and at times slightly amsuing results. Eg being able to see grouped by first name who uses the most mailbox resources is kind of funny. You could go take this little further use the persons birthday to figure their star sign and then show mailbox size usage by signs of the zodiac.

(If your looking for OU its added as the last item in the Drop down list)

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

[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
$form = new-object System.Windows.Forms.form

$usrinfo = @{ }
$ctab = @{ }
$agDepartment = @{ }
$agOffice = @{ }
$htAg = @{ }
$ExcomCollection = @()
function Aggresults{
$htAg.clear()
if ($mtTypeDrop.SelectedItem -eq $null){
$agMethod = "LastName"
}
else{
$agMethod = $mtTypeDrop.SelectedItem.ToString()
}
foreach ($row in $usrinfo.Values){
if ($row.$agMethod.ToString() -eq ""){
if ($htAg.containskey("Not Set")){
$htAg["Not Set"].Number = $htAg["Not Set"].Number + 1
$htAg["Not Set"].Size = $htAg["Not Set"].Size + [INT]$row.MailboxSize.ToString()
}
else{
$mbcnt = "" | select Name,Number,Size
$mbcnt.Name = "Not Set"
$mbcnt.Number = 1
$mbcnt.Size = [INT]$row.MailboxSize.ToString()
$htAg.Add("Not Set",$mbcnt)

}
}
else{
if ($htAg.containskey($row.$agMethod.ToString())){
$htAg[$row.$agMethod.ToString()].Number = $htAg[$row.$agMethod.ToString()].Number + 1
$htAg[$row.$agMethod.ToString()].Size = $htAg[$row.$agMethod.ToString()].Size + [INT]$row.MailboxSize.ToString()
}
else{
$row.$agMethod.ToString()
$mbcnt = "" | select Name,Number,Size
$mbcnt.Name = $row.$agMethod.ToString()
$mbcnt.Number = 1
$mbcnt.Size = [INT]$row.MailboxSize.ToString()
$htAg.Add($row.$agMethod.ToString(),$mbcnt)
}
}
}
$agtable.Clear()
$valueBlock = ""
$TitleBlock = ""
$TitleBlock1 = ""
foreach ($row in $htAg.Values){
$agtable.rows.add($row.Name,$row.Number,$row.Size)
if ($valueBlock -eq ""){$valueBlock = $row.Size.ToString()
$lval = [INT]$row.Size
}
else {
$valueBlock = $valueBlock + "," + $row.Size.ToString()
if ($lval -lt [INT]$row.Size){$lval = [INT]$row.Size}
}
if ($TitleBlock -eq ""){$TitleBlock = $row.Name.ToString().Replace("&","-")
$TitleBlock1 = $row.Name.ToString().Replace("&","-")
}
else {$TitleBlock = $TitleBlock + "|" + $row.Name.ToString().Replace("&","-")
$TitleBlock1 = $row.Name.ToString().Replace("&","-") + "|" + $TitleBlock1
}
}
$csString = "http://chart.apis.google.com/chart?cht=p3&chs=430x160&chds=0," + $lval + "&chd=t:" + $valueBlock + "&chl=" + $TitleBlock + "&chco=0000ff,00ff00,ff0000,FFFFFF,000000"
$pbox.ImageLocation = $csString
$csString1 = "http://chart.apis.google.com/chart?cht=bhs&chs=530x300&chd=t:" + $valueBlock + "&chds=0," + ($lval+20) + "&chxt=x,y&chbh=a&chxr=" + "&chxr=0,0," + ($lval+20) + "&chxl=1:|" + $TitleBlock1 + "&chco=0000ff,00ff00,ff0000,FFFFFF,000000"
$pbox1.ImageLocation = $csString1
$dgDataGrid.DataSource = $agtable
}

function getMailboxSizes(){

$mbcombCollection = @()
$usrinfo.clear()
$ctab.clear()
$agDepartment.clear()
$agOffice.clear()
$ExcomCollection = @()
$agtable.clear()

$serverName = $snServerNameDrop.SelectedItem.ToString()
if ($snServerNameDrop.SelectedItem.ToString() -eq "ALL Servers"){
$mailboxes = get-mailbox -ResultSize Unlimited
}
else{
$mailboxes = get-mailbox -server $snServerNameDrop.SelectedItem.ToString() -ResultSize Unlimited
}
$mailboxes | foreach-object{
$ctab.add($_.Guid.ToString(),$_.ExchangeGuid)
}
"Finished Get Mailbox"
Get-User -recipienttype UserMailbox -ResultSize Unlimited | foreach-object{
if ($ctab.ContainsKey($_.Guid.ToString())){
$usrobj = $_ | select *,MailboxSize,ExchangeGUID,OU
$oustring = ""
$idarry = $_.Identity.ToString().Split("/")
for($i=1;$i-lt ($idarry.length-1);$i++){
$oustring = $oustring + "\" + $idarry[$i]
}
$usrobj.OU = $oustring
$usrobj.ExchangeGUID = $ctab[$_.Guid.ToString()]
$usrinfo.add($ctab[$_.Guid.ToString()].ToString(),$usrobj)
}

}
$mbServers = get-mailboxserver
if ($snServerNameDrop.SelectedItem.ToString() -eq "ALL Servers"){
$mbServers | foreach-object{

$mscombCollection += get-mailboxstatistics -server $_.Name | Where {$_.DisconnectDate -eq $null}

}
}
else{
$mscombCollection += get-mailboxstatistics -server $snServerNameDrop.SelectedItem.ToString() | Where {$_.DisconnectDate -eq $null}
}

$mscombCollection | ForEach-Object{
$usrobj = $usrinfo[$_.MailboxGuid.ToString()]
if ($usrinfo.ContainsKey($_.MailboxGuid.ToString())){
if ($_.TotalItemSize.Value.ToMB() -ne $null){
$usrobj.MailboxSize = $_.TotalItemSize.Value.ToMB()
}
else
{
$usrobj.MailboxSize = 0
}
}

}
Aggresults
}

function ShowMailboxes(){
if ($mtTypeDrop.SelectedItem -eq $null){
$agMethod = "LastName"
}
else{
$agMethod = $mtTypeDrop.SelectedItem.ToString()
}
$mbtable = New-Object System.Data.DataTable
$mbtable.TableName = "Mailboxes"
$mbtable.Columns.Add("Display Name")
$mbtable.Columns.Add($agMethod)
$mbtable.Columns.Add("Mailbox Size(MB)",[int64])
foreach ($row in $usrinfo.Values){
if($row.$agMethod -eq $agtable.DefaultView[$dgDataGrid.CurrentCell.RowIndex][0]){
$mbtable.rows.add($row.DisplayName,$row.$agMethod,$row.MailboxSize)
}
else{
if($row.$agMethod -eq ""){
if("Not Set" -eq $agtable.DefaultView[$dgDataGrid.CurrentCell.RowIndex][0]){
$mbtable.rows.add($row.DisplayName,$row.$agMethod,$row.MailboxSize)
}
}
}
}
$dgDataGrid1.DataSource = $mbtable
}

function ExportGrid1csv{

$exFileName = new-object System.Windows.Forms.saveFileDialog
$exFileName.DefaultExt = "csv"
$exFileName.Filter = "csv files (*.csv)|*.csv"
$exFileName.InitialDirectory = "c:\temp"
$exFileName.ShowHelp = $true
$exFileName.ShowDialog()
if ($exFileName.FileName -ne ""){
$logfile = new-object IO.StreamWriter($exFileName.FileName,$true)
$logfile.WriteLine("DisplayName,Number of Mailboxes,Mailbox Size(MB)")
foreach($row in $agTable.Rows){
$logfile.WriteLine("`"" + $row[0].ToString() + "`"," + $row[1].ToString() + "," + $row[2].ToString())
}
$logfile.Close()
}
}

function ExportGrid2csv{

$exFileName = new-object System.Windows.Forms.saveFileDialog
$exFileName.DefaultExt = "csv"
$exFileName.Filter = "csv files (*.csv)|*.csv"
$exFileName.InitialDirectory = "c:\temp"
$exFileName.ShowHelp = $true
$exFileName.ShowDialog()
if ($exFileName.FileName -ne ""){
$logfile = new-object IO.StreamWriter($exFileName.FileName,$true)
$logfile.WriteLine("DisplayName,Office,Department,Mailbox Size(MB)")
foreach($row in $mbtable.Rows){
$logfile.WriteLine("`"" + $row[0].ToString() + "`"," + $row[1].ToString() + "," + $row[2].ToString())
}
$logfile.Close()
}
}

$agtable = New-Object System.Data.DataTable
$agtable.TableName = "Mailbox Sizes"
$agtable.Columns.Add("Name")
$agtable.Columns.Add("# Mailboxes",[int64])
$agtable.Columns.Add("Mailbox Size(MB)",[int64])




# Add Server DropLable
$snServerNamelableBox = new-object System.Windows.Forms.Label
$snServerNamelableBox.Location = new-object System.Drawing.Size(10,20)
$snServerNamelableBox.size = new-object System.Drawing.Size(80,20)
$snServerNamelableBox.Text = "ServerName"
$form.Controls.Add($snServerNamelableBox)

# Add Server Drop Down
$snServerNameDrop = new-object System.Windows.Forms.ComboBox
$snServerNameDrop.Location = new-object System.Drawing.Size(90,20)
$snServerNameDrop.Size = new-object System.Drawing.Size(100,30)
get-mailboxserver | ForEach-Object{$snServerNameDrop.Items.Add($_.Name)}
$snServerNameDrop.Items.Add("ALL Servers")
$snServerNameDrop.Add_SelectedValueChanged({getMailboxSizes})

$form.Controls.Add($snServerNameDrop)

# Add Agregate Type DropLable
$mtTypeDroplableBox = new-object System.Windows.Forms.Label
$mtTypeDroplableBox.Location = new-object System.Drawing.Size(200,20)
$mtTypeDroplableBox.size = new-object System.Drawing.Size(70,20)
$mtTypeDroplableBox.Text = "Group By"
$form.Controls.Add($mtTypeDroplableBox)

# Add Mailbox Type Drop Down
$mtTypeDrop = new-object System.Windows.Forms.ComboBox
$mtTypeDrop.Location = new-object System.Drawing.Size(270,20)
$mtTypeDrop.Size = new-object System.Drawing.Size(135,30)
$properties = get-user -resultsize 1 | get-member -membertype Property
foreach ($prop in $properties){
$mtTypeDrop.Items.Add($prop.Name)
}
$mtTypeDrop.Items.Add("OU")
$mtTypeDrop.Add_SelectedValueChanged({Aggresults})
$form.Controls.Add($mtTypeDrop)

# Show Mailboxs Button

$shMailboxes = new-object System.Windows.Forms.Button
$shMailboxes.Location = new-object System.Drawing.Size(600,19)
$shMailboxes.Size = new-object System.Drawing.Size(120,23)
$shMailboxes.Text = "Show Mailboxes"
$shMailboxes.visible = $True
$shMailboxes.Add_Click({ShowMailboxes})
$form.Controls.Add($shMailboxes)

# Add Export Grid Button

$exButton1 = new-object System.Windows.Forms.Button
$exButton1.Location = new-object System.Drawing.Size(430,19)
$exButton1.Size = new-object System.Drawing.Size(90,23)
$exButton1.Text = "Export Grid"
$exButton1.Add_Click({ExportGrid1csv})
$form.Controls.Add($exButton1)

# Add Export Grid Button 2

$exButton2 = new-object System.Windows.Forms.Button
$exButton2.Location = new-object System.Drawing.Size(750,19)
$exButton2.Size = new-object System.Drawing.Size(125,23)
$exButton2.Text = "Export Grid"
$exButton2.Add_Click({ExportGrid2csv})
$form.Controls.Add($exButton2)

#add Picture box

$pbox = new-object System.Windows.Forms.PictureBox
$pbox.Location = new-object System.Drawing.Size(550,360)
$pbox.Size = new-object System.Drawing.Size(500,220)
$form.Controls.Add($pbox)

$pbox1 = new-object System.Windows.Forms.PictureBox
$pbox1.Location = new-object System.Drawing.Size(10,360)
$pbox1.Size = new-object System.Drawing.Size(550,370)
$form.Controls.Add($pbox1)

# Add DataGrid View

$dgDataGrid = new-object System.windows.forms.DataGridView
$dgDataGrid.Location = new-object System.Drawing.Size(10,50)
$dgDataGrid.size = new-object System.Drawing.Size(530,300)
$dgDataGrid.AutoSizeRowsMode = "AllHeaders"
$form.Controls.Add($dgDataGrid)

$dgDataGrid1 = new-object System.windows.forms.DataGridView
$dgDataGrid1.Location = new-object System.Drawing.Size(550,50)
$dgDataGrid1.size = new-object System.Drawing.Size(450,300)
$dgDataGrid1.AutoSizeRowsMode = "AllHeaders"
$form.Controls.Add($dgDataGrid1)

$form.Text = "Exchange 2007 Group by Mailbox Size Form"
$form.size = new-object System.Drawing.Size(1000,700)
$form.autoscroll = $true
$form.Add_Shown({$form.Activate()})
$form.ShowDialog()