Tuesday, May 01, 2007

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 = " ";
}
}
}
}

16 comments:

Dean said...

None of the appointments are showing up. The pages runs fine but no appointments are displaying

Dean said...

Correction...they are displaying but 14 hours behind.

Glen said...

Sorry there's a bug with the timezone code your probably having there's an updated function and explanation in http://gsexdev.blogspot.com/2007/04/understanding-timezone-setting-with.html

I just haven't had time to update this post its on the list of thing to do

cheers
Glen

Glen said...

Okay I've updated the code in the download

Dean said...

Thanks!!! This code has saved me a great deal of research time.

John said...

Hi Glen,

Firstly since I have a working implementation this has been a great resource so thanks.

I have 2 queries:

Firstly I want have an option of day view, week view or month view. Is this something that could be easily done?

Secondly I would like to be able to specify a url IE http://casserver/MeetingRooms?user=johnsmith,email=john@smith.com

The URL would decide which user to pull through the mailbox of, is this possible?

I'm trying to use this to replace the need to sync calendars w/ google calendars and publish from there.

Thanks again!

Glen said...

You really need to develop your own solution while you could reuse some of the ideas and code in this post its not really applicable to what you want to do and would require that you think about and code it diffently. Eg you would use Resourcefind if you are passing in parameter via QueryStrings. The Day/month/week would requires that you code your own display solution.


Cheers
Glen

Anonymous said...

Hi this is exactly what I need, except I've installed and am getting an error saying:

Compilation Error,
An Error occured during the compilation of a resource required to service this request...

Line 17: using ResourceFind;

I'm quite new to asp.net so please fogive me if its obvious!! Thanks in advance!

Glen said...

It requires that you have the ResourceFind Web Service setup and running from my other post http://gsexdev.blogspot.com/2007/04/webservice-to-find-room-and-equipment.html. This is use to feed in the array of Resource mailboxes to check.

I've posted up a complete working virtual directory http://msgdev.mvps.org/meetingroom.zip you do need to make the virtual directory these files are place a web application see http://msdn2.microsoft.com/en-us/library/ha2y9493.aspx .

Cheers
Glen

Andrew said...

I was looking for the zip file that you put a link to here (the Virtual directory zip file on mvps.org) and it seems to have gone. Any chance of getting it again, or perhaps via email? (andrew"dot"proctor"at"mxi"dot"com)

Cheers muchly!

Andrew said...

Glen

Just wanted to say thanks very much. Using your code I have managed to get somethng working and can now tweak it for my specific needs. I really appreciate the time and effort you ahve taken to provide this sort of thing for idiots like me, I don't know a lot about this side of things (I'm an windows/exchange sysadmin), but using your samples to do real world work (rather than some theoretical "Hello World" type app) has got me reading more and I'm learning something! So thanks very much.

Edwin said...

Hi,

Thanks for all your post they are preatty helpful. With respect to resource mailbox availabilty. I am able to retrieve the start and end times for the schedule event. However, when I try to retrieve the CalendarEventDetails from the fbResponse.FreeBusyResponseArray[mbNumCount].FreeBusyView.CalendarEventArray. The CalendarEventDetails object is set to null. Is there some powershell command or utility I have to run that will allows the details to be included in the response.

Glen said...

You need to make sure the calendar you querying allows Subject and location details permissions to the user that making the FB query. By default the rights will only allow you to see Date/Time information.

Cheers
Glen

Kai said...

Hi Glen,

where could be the Problem when Appointments are not associated to the correct room???

Means:
App1, App2 in Room1
App3, App4 in Room2
App5, App6 in Room3

Get displayed this way:
Room1: App3, App4
Room2: App1, App2
Room3: App5, App6

cheers
Kai

Pavle said...

Hello, first - thanks a lot for Your Blog. I have same problem like Kai. My appointments as showed for wrong room. They are moved for +20 room (I have 65 rooms). What could I do?

Anonymous said...

Hello, where can i Download this ScriptCode..
The Link is not responding..