Skip to main content

Resource Mailbox availability web page for Exchange 2007

One of the coolest new things about Exchange Web Services on Exchange 2007 is the GetUserAvailability operation. This operation gives you the ability to get the Free-busy information about a number of users with one request and also not just only whether the users are free or busy which by itself has limited use but where this adds value is that you can also request to see the basic information about the calendar appointments a user is involved in. This makes it a great building block for any small team calendars or collaborative apps you are trying to build. It’s also good if you want to build availability pages for resource mailboxes which is what I’ve used it for in this post.

To provide information in a Internet portal what i put together was an Asp.net page that first makes a request to the Find Room WebService I posted the other day. This WebService returns a list of Email Address’s and DisplayName’s which can then be used in a GetUserAvailability request which will then retrieve the freebusy times for the mailboxes returned from the Find Room Query and the detail of those appointments. To display the appointments to the user I’ve used a datagrid which uses as a datasource a datatable created from the result of the GetUserAvailability operation that is formatted specifically in a time Grid. To do specific row formatting and color changes and row spans I’ve used the data-binding event to map alternate colors for each Meeting and change row span setting to the number of hours an appointment is scheduled for. This produces something that looks like the following

The code is set to query a time period within one day eg business hours from 8 AM - 6 PM (you can adjust this using variables in the code).To cater for many combinations the logic in the code allows for all day appointments, appointments that start before the time period and appointments that end after the time period and as many other scenarios I could think of. The codes designed to run around the default 30 minute interval period it can be adapted for other intervals but requires a little bit more logic.

The Anatomy of code is first there is a stub to deal with self signed certs (this needs to be extended out a bit in production). Then the FindRoom sub runs which returns all the rooms in AD. The Freebusy request timezone information is then configured as per my other post the other day. The results are format into a Datatable which is then bound to the datagrid. To do the default Table formatting I’ve used a Style sheet and then for the specific formatting of each of the appointments this is done though the databinding event for each row in the datagrid.

Before using the Code you need to configure the following variables either via the code of via a webConfig file. To use the GetUserAvailability Operation you need make the request with a security context of a user that either has a mailbox or has been granted impersonation rights. The ServerName is the server that is hosting EWS.

String unUserName = "usrName";
String pnPassWord = "password";
String dnDomain = "domain";
String snServerName = "CASservername";
String stStartTime = "08:00:00";
String etEndTime = "18:00:00";

I’ve put a downloadable copy of the code and Asp.net page here the code itself looks

private struct SYSTEMTIME
{
public Int16 wYear;
public Int16 wMonth;
public Int16 wDayOfWeek;
public Int16 wDay;
public Int16 wHour;
public Int16 wMinute;
public Int16 wSecond;
public Int16 wMilliseconds;
public void getSysTime(byte[] Tzival, int offset)
{
wYear = BitConverter.ToInt16(Tzival, offset);
wMonth = BitConverter.ToInt16(Tzival, offset + 2);
wDayOfWeek = BitConverter.ToInt16(Tzival, offset + 4);
wDay = BitConverter.ToInt16(Tzival, offset + 6);
wHour = BitConverter.ToInt16(Tzival, offset + 8);
wMinute = BitConverter.ToInt16(Tzival, offset + 10);
wSecond = BitConverter.ToInt16(Tzival, offset + 12);
wMilliseconds = BitConverter.ToInt16(Tzival, offset + 14);
}
}
private struct REG_TZI_FORMAT
{
public Int32 Bias;
public Int32 StandardBias;
public Int32 DaylightBias;
public SYSTEMTIME StandardDate;
public SYSTEMTIME DaylightDate;
public void regget(byte[] Tzival)
{
Bias = BitConverter.ToInt32(Tzival, 0);
StandardBias = BitConverter.ToInt32(Tzival, 4);
DaylightBias = BitConverter.ToInt32(Tzival, 8);
StandardDate = new SYSTEMTIME();
StandardDate.getSysTime(Tzival, 12);
DaylightDate = new SYSTEMTIME();
DaylightDate.getSysTime(Tzival, 28);
}


String unUserName = "username";
String pnPassWord = "password";
String dnDomain = "domain";
String snServerName = "servername";
String stStartTime = "08:00:00";
String etEndTime = "18:00:00";

//Deal with Self Signed Certificate Errors
ServicePointManager.ServerCertificateValidationCallback = delegate(Object obj,
X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
};

DataTable raDataTable = new DataTable();
raDataTable.Columns.Add("Time");
//Define FreeBusy Connection
ExchangeServiceBinding ewsServiceBinding = new ExchangeServiceBinding();
ewsServiceBinding.Credentials = new NetworkCredential(unUserName, pnPassWord ,dnDomain
);
ewsServiceBinding.Url = @"https://" + snServerName + "/EWS/exchange.asmx";
Duration fbDuration = new Duration();
fbDuration.StartTime = DateTime.ParseExact(DateTime.Now.ToString("yyyyMMdd") +
"T" + stStartTime, "yyyyMMddTHH:mm:ss", null);
fbDuration.EndTime = DateTime.ParseExact(DateTime.Now.ToString("yyyyMMdd") + "T"
+ etEndTime , "yyyyMMddTHH:mm:ss", null);
int itIntevalNum = DateTime.Compare(fbDuration.StartTime, fbDuration.EndTime);

//Deal with timeZone in Request
String tzString = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\" + TimeZone.CurrentTimeZone.StandardName;
RegistryKey TziRegKey = Registry.LocalMachine;
TziRegKey = TziRegKey.OpenSubKey(tzString);
byte[] Tzival = (byte[])TziRegKey.GetValue("TZI");
REG_TZI_FORMAT rtRegTimeZone = new REG_TZI_FORMAT();
rtRegTimeZone.regget(Tzival);
GetUserAvailabilityRequestType fbRequest = new GetUserAvailabilityRequestType();
fbRequest.TimeZone = new SerializableTimeZone();
fbRequest.TimeZone.DaylightTime = new SerializableTimeZoneTime();
fbRequest.TimeZone.StandardTime = new SerializableTimeZoneTime();
fbRequest.TimeZone.Bias = rtRegTimeZone.Bias;
fbRequest.TimeZone.StandardTime.Bias = rtRegTimeZone.StandardBias;
fbRequest.TimeZone.DaylightTime.Bias = rtRegTimeZone.DaylightBias;
if (rtRegTimeZone.StandardDate.wMonth != 0)
{
fbRequest.TimeZone.StandardTime.DayOfWeek = ((DayOfWeek)rtRegTimeZone.StandardDate.wDayOfWeek).ToString();
fbRequest.TimeZone.StandardTime.DayOrder = (short)rtRegTimeZone.StandardDate.wDay;
fbRequest.TimeZone.StandardTime.Month = rtRegTimeZone.StandardDate.wMonth;
fbRequest.TimeZone.StandardTime.Time = String.Format("{0:0#}:{1:0#}:{2:0#}", rtRegTimeZone.StandardDate.wHour, rtRegTimeZone.StandardDate.wMinute, rtRegTimeZone.StandardDate.wSecond);
}
else
{
fbRequest.TimeZone.StandardTime.DayOfWeek = "Sunday";
fbRequest.TimeZone.StandardTime.DayOrder = 1;
fbRequest.TimeZone.StandardTime.Month = 1;
fbRequest.TimeZone.StandardTime.Time = "00:00:00";

}
if (rtRegTimeZone.DaylightDate.wMonth != 0)
{
fbRequest.TimeZone.DaylightTime.DayOfWeek = ((DayOfWeek)rtRegTimeZone.DaylightDate.wDayOfWeek).ToString();
fbRequest.TimeZone.DaylightTime.DayOrder = (short)rtRegTimeZone.DaylightDate.wDay;
fbRequest.TimeZone.DaylightTime.Month = rtRegTimeZone.DaylightDate.wMonth;
fbRequest.TimeZone.DaylightTime.Time = "00:00:00";
}
else
{
fbRequest.TimeZone.DaylightTime.DayOfWeek = "Sunday";
fbRequest.TimeZone.DaylightTime.DayOrder = 5;
fbRequest.TimeZone.DaylightTime.Month = 12;
fbRequest.TimeZone.DaylightTime.Time = "23:59:59";

}
fbRequest.MailboxDataArray = mbMailboxes;
fbRequest.FreeBusyViewOptions = fbViewOptions;
GetUserAvailabilityResponseType fbResponse = ewsServiceBinding.GetUserAvailability(fbRequest);
System.TimeSpan ftsTimeSpan = fbDuration.EndTime - fbDuration.StartTime;
double frspan = ftsTimeSpan.TotalMinutes / 30;
int tsseg = 0;
for (DateTime htStartTime = fbDuration.StartTime; htStartTime <
fbDuration.EndTime; htStartTime = htStartTime.AddMinutes(30))
{
DataRow drDataRow = raDataTable.NewRow();
drDataRow[0] = htStartTime.ToString("HH:mm");
for (int mbNumCount = 0; mbNumCount < mbMailboxes.Length; mbNumCount++)
{
rvRowValue =
fbResponse.FreeBusyResponseArray[mbNumCount].FreeBusyView.MergedFreeBusy.Substring(tsseg,
1);
if (rvRowValue != "0") {
foreach (CalendarEvent calevent in
fbResponse.FreeBusyResponseArray[mbNumCount].FreeBusyView.CalendarEventArray) {
System.TimeSpan tsTimeSpan = calevent.EndTime - calevent.StartTime;
double rspan = tsTimeSpan.TotalMinutes / 30;
if (htStartTime.ToString("HH:mm") == fbDuration.StartTime.ToString("HH:mm"))
{
if (rspan >= 48)
{
if (calevent.CalendarEventDetails != null)
{
if (calevent.CalendarEventDetails.Subject != "")
{
rvRowValue = frspan + " " + calevent.CalendarEventDetails.Subject;
}
else {
rvRowValue = frspan + " Occupied";
}

}
else
{
rvRowValue = frspan + " Occupied";
}

}
else if (calevent.StartTime < fbDuration.StartTime)
{
System.TimeSpan stTimeSpan = fbDuration.StartTime - calevent.StartTime;
double stspan = stTimeSpan.TotalMinutes / 30;
if (calevent.CalendarEventDetails != null)
{
if (calevent.CalendarEventDetails.Subject != "")
{
rvRowValue = (rspan - stspan) + " " + calevent.CalendarEventDetails.Subject;
}
else {
rvRowValue = (rspan - stspan) + " Occupied";
}
}
else
{
rvRowValue = (rspan - stspan) + " Occupied";
}
}
}
if (htStartTime == calevent.StartTime)
{
if (calevent.CalendarEventDetails != null)
{
if (calevent.CalendarEventDetails.Subject != "")
{
rvRowValue = rspan.ToString() + " " + calevent.CalendarEventDetails.Subject;
}
else {
rvRowValue = rspan.ToString() + " Occupied";
}
}
else {
rvRowValue = rspan.ToString() + " Occupied";
}
}
}
}
drDataRow[mbNumCount + 1] = rvRowValue;
}
raDataTable.Rows.Add(drDataRow);
tsseg++;
}
dgDataGrid.DataSource = raDataTable;
dgDataGrid.DataBind();
}
public void dgDataGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].BackColor = Color.LightGray;
e.Row.Cells[0].Font.Bold = true;
for (int cnColNumber = 1; cnColNumber < e.Row.Cells.Count;cnColNumber++ ){
e.Row.Cells[cnColNumber].Width = 150;
if (e.Row.Cells[cnColNumber].Text.Substring(0,1) != "0") {
if ((cnColNumber % 2) == 0)
{
e.Row.Cells[cnColNumber].BackColor = Color.LightGreen;
}
else {
e.Row.Cells[cnColNumber].BackColor = Color.LightBlue;
}
if (e.Row.Cells[cnColNumber].Text.Length > 2)
{
string rspan = e.Row.Cells[cnColNumber].Text.Substring(0, 2).ToString();
e.Row.Cells[cnColNumber].Text = e.Row.Cells[cnColNumber].Text.Substring(2,
(e.Row.Cells[cnColNumber].Text.Length - 2));
e.Row.Cells[cnColNumber].RowSpan = Convert.ToInt16(rspan);
}
else
{
e.Row.Cells[cnColNumber].Visible = false;
e.Row.Cells[cnColNumber].Text = " ";
}
}
else {e.Row.Cells[cnColNumber].Text = " ";
}
}
}
}

Popular posts from this blog

Testing and Sending email via SMTP using Opportunistic TLS and oAuth in Office365 with PowerShell

As well as EWS and Remote PowerShell (RPS) other mail protocols POP3, IMAP and SMTP have had OAuth authentication enabled in Exchange Online (Official announcement here ). A while ago I created  this script that used Opportunistic TLS to perform a Telnet style test against a SMTP server using SMTP AUTH. Now that oAuth authentication has been enabled in office365 I've updated this script to be able to use oAuth instead of SMTP Auth to test against Office365. I've also included a function to actually send a Message. Token Acquisition  To Send a Mail using oAuth you first need to get an Access token from Azure AD there are plenty of ways of doing this in PowerShell. You could use a library like MSAL or ADAL (just google your favoured method) or use a library less approach which I've included with this script . Whatever way you do this you need to make sure that your application registration  https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-

How to test SMTP using Opportunistic TLS with Powershell and grab the public certificate a SMTP server is using

Most email services these day employ Opportunistic TLS when trying to send Messages which means that wherever possible the Messages will be encrypted rather then the plain text legacy of SMTP.  This method was defined in RFC 3207 "SMTP Service Extension for Secure SMTP over Transport Layer Security" and  there's a quite a good explanation of Opportunistic TLS on Wikipedia  https://en.wikipedia.org/wiki/Opportunistic_TLS .  This is used for both Server to Server (eg MTA to MTA) and Client to server (Eg a Message client like Outlook which acts as a MSA) the later being generally Authenticated. Basically it allows you to have a normal plain text SMTP conversation that is then upgraded to TLS using the STARTTLS verb. Not all servers will support this verb so if its not supported then a message is just sent as Plain text. TLS relies on PKI certificates and the administrative issue s that come around certificate management like expired certificates which is why I wrote th

The MailboxConcurrency limit and using Batching in the Microsoft Graph API

If your getting an error such as Application is over its MailboxConcurrency limit while using the Microsoft Graph API this post may help you understand why. Background   The Mailbox  concurrency limit when your using the Graph API is 4 as per https://docs.microsoft.com/en-us/graph/throttling#outlook-service-limits . This is evaluated for each app ID and mailbox combination so this means you can have different apps running under the same credentials and the poor behavior of one won't cause the other to be throttled. If you compared that to EWS you could have up to 27 concurrent connections but they are shared across all apps on a first come first served basis. Batching Batching in the Graph API is a way of combining multiple requests into a single HTTP request. Batching in the Exchange Mail API's EWS and MAPI has been around for a long time and its common, for email Apps to process large numbers of smaller items for a variety of reasons.  Batching in the Graph is limited to a m
All sample scripts and source code is provided by for illustrative purposes only. All examples are untested in different environments and therefore, I cannot guarantee or imply reliability, serviceability, or function of these programs.

All code contained herein is provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.