Friday, January 25, 2008

Setting and Understanding Folder Permissions in Exchange Web Services

One of the more challenging things you may want to do when writing code that is going to run against an Exchange 2007 mailbox is to set and modify Folder permissions on a mailbox folder or a public folder. I’d thought I’d share my efforts and what I learnt over the last week of trying to do this (thanks to David Claux for helping me get over my issues with custom permissions). One of the features added to SP1 in Exchange 2007 is the ability to set folder permissions and also folder delegates. This is a pretty cool feature but one you do need to make sure you understand before you dive in. Before you start its a good idea to understand the permissions your want to modify to ensure your code is going to work as expected and avoid any unwanted ACL changes.

Let’s start by looking at the permissions that can be set on a folder via EWS

CanCreateItems
ReadItems
DeleteItems
EditItems
CanCreateSubFolders
IsFolderContact
IsFolderOwner
IsFolderVisible

With Exchange 2007/Outlook2007 there where Permissions added to support the new freebusy detail features in Outlook and Exchange. There’s some good information about these on Stephen Griffin's Blog . These new permissions are only valid for a calendar folder. Overlaying these based folder permissions are the Roles that a user would generally assign in Outlook. Now these Roles are just certain combinations of the above Permissions. The following are the roles you would normally see set on a folder if you’re looking in Outlook

Author
Contributor
Custom
Editor
None
NoneditingAuthor
Owner
PublishingAuthor
PublishingEditor
Reviewer

On a calendar folder you have the following additional roles to support freebusy detail

FreeBusyTimeAndSubjectAndLocation
FreeBusyTimeOnly

Now let’s look at an example of setting the calendar folder permissions using EWS. Generally when you are setting permissions you’ll be modifying the permissions on an already existing Exchange Store object. So you will be either adding an additional Access Control Entry to the permissions list or modifying the rights or an existing ACE.

In EWS calendar folder permissions are represented by the CalendarPermissionSetType object so to modify the permissions on an existing folder you need to modify the Permission Set property using an updateitem operation. Sounds easy right well this is where the complications begin.

When you use an UpdateItem operation to update a property on a folder that property you update will overwrite the existing store property. Because the whole PermissionSet is represented as one property you can’t just write the changes with an UpdateItem operation. If you do this you will end up deleting all your existing ACE’s and end up only with the changes you’re trying to make. So to cater for this you first need to get the existing CalendarPermissionSet using a GetFolder operation, you then need to create a new CalendarPermissionSet that contains all the ACE’s from the existing CalendarPermissionSet with whatever modifications you want and then post this new CalendarPermissionSet to overwrite the existing set. Now here’s a precautionary tale don’t do what I tried to which was to try and just make changes to the existing CalendarPermissionSet object you retrieve with GetFolder operation and then post this back.

The reason this could fail is also a little complicated but there are a few important points to understand.

When you include a calendarPermission in a CalendarPermissionSet you have to set the CalendarPermissionLevel. These Levels relate to the Outlook Roles I mentioned previously if these roles are set to anything other than Custom you must make sure you don’t include setting any of the base rights. So basically you can set something like the CalendarPermissionLevel to PublishingAuthor or you can set the CalendarPermissionLevel to custom and then set each of the base rights like CanCreateItems,ReadItems etc. If you try to set CalendarPermissionLevel to PublishingAuthor and also set the base rights (including the foldercontact and folderowner setting) EWS will reject the changes you’re trying to make as invalid.

Now when you get the permissionset using a GetFolder operation EWS will return a fully populated CalendarPermission object for each ACE in the Set even if the CalendarPermissionLevel isn’t set to custom. So if you try to use one of these calendarPermissions that had a CalendarPermissionLevel set to something other than custom it will cause your code to error out because it breaks the rule I mentioned in the last paragraph.

So from a coding perspective to make this work you should build a new CalendarPermissionLevel object based on the existing object with some logic to verify the CalendarPermission your including in the set is going to be valid. The logic I came up with was you can copy any of the existing custom CalendarPermissionLevel objects okay into the new CalendarPermissionSet object but for any other role you need to create a new CalendarPermission object and just copy the userid and CalendarPermissionLevel from the existing CalendarPermission.

The one thing to be careful of if you are setting Public Folder permission with EWS and you have set custom folder contacts is you may in some situations lose your custom contact folder setting if you set permissions using EWS and you don’t use the Custom Level.

So to put this all together in a code sample the following piece of code will change the default permissions on a user’s calendar from none to editor. I’ve put a download of this code here the code itself looks like.

static void Main(string[] args)
{
// Create the binding and set the credentials
ExchangeServiceBinding esb = new ExchangeServiceBinding();
esb.RequestServerVersionValue = new RequestServerVersion();
esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007_SP1;
ServicePointManager.ServerCertificateValidationCallback =
delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
// Replace this line with code to validate server certificate.
return true;
};

esb.Credentials = new NetworkCredential("username", "password", "domain");
esb.Url = @"https://servername/EWS/Exchange.asmx";
setcalperm(esb);

}
static void setcalperm(ExchangeServiceBinding esb)
{

DistinguishedFolderIdType cfCurrentCalendar = new DistinguishedFolderIdType();
cfCurrentCalendar.Id = DistinguishedFolderIdNameType.calendar;

FolderResponseShapeType frFolderRShape = new FolderResponseShapeType();
frFolderRShape.BaseShape = DefaultShapeNamesType.AllProperties;

GetFolderType gfRequest = new GetFolderType();
gfRequest.FolderIds = new BaseFolderIdType[1] { cfCurrentCalendar };
gfRequest.FolderShape = frFolderRShape;


GetFolderResponseType gfGetFolderResponse = esb.GetFolder(gfRequest);
CalendarFolderType cfCurrentFolder = null;
if (gfGetFolderResponse.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Success)
{

cfCurrentFolder = (CalendarFolderType)((FolderInfoResponseMessageType)gfGetFolderResponse.ResponseMessages.Items[0]).Folders[0];

}
else
{//handle error
}

UserIdType auAceUser = new UserIdType();
auAceUser.DistinguishedUserSpecified = true;
auAceUser.DistinguishedUser = DistinguishedUserType.Default;

CalendarPermissionSetType cfCurrentCalPermsionsSet = cfCurrentFolder.PermissionSet;
CalendarPermissionSetType cfNewCalPermsionsSet = new CalendarPermissionSetType();
cfNewCalPermsionsSet.CalendarPermissions = new CalendarPermissionType[cfCurrentCalPermsionsSet.CalendarPermissions.Length] ;
for(int cpint=0;cpint < cfCurrentCalPermsionsSet.CalendarPermissions.Length;cpint++){
if (cfCurrentCalPermsionsSet.CalendarPermissions[cpint].UserId.SID == auAceUser.SID)
{
cfNewCalPermsionsSet.CalendarPermissions[cpint] = new CalendarPermissionType();
cfNewCalPermsionsSet.CalendarPermissions[cpint].UserId = cfCurrentCalPermsionsSet.CalendarPermissions[cpint].UserId;
cfNewCalPermsionsSet.CalendarPermissions[cpint].CalendarPermissionLevel = CalendarPermissionLevelType.Reviewer;
}
else
{
//Copy old ACE
if (cfCurrentCalPermsionsSet.CalendarPermissions[cpint].CalendarPermissionLevel == CalendarPermissionLevelType.Custom)
{
cfNewCalPermsionsSet.CalendarPermissions[cpint] = cfCurrentCalPermsionsSet.CalendarPermissions[cpint];
}
else
{
cfNewCalPermsionsSet.CalendarPermissions[cpint] = new CalendarPermissionType();
{
cfNewCalPermsionsSet.CalendarPermissions[cpint].UserId = cfCurrentCalPermsionsSet.CalendarPermissions[cpint].UserId;
cfNewCalPermsionsSet.CalendarPermissions[cpint].CalendarPermissionLevel = cfCurrentCalPermsionsSet.CalendarPermissions[cpint].CalendarPermissionLevel;
}
}
}

}


CalendarFolderType cfUpdateCalFolder = new CalendarFolderType();
cfUpdateCalFolder.PermissionSet = cfNewCalPermsionsSet;

UpdateFolderType upUpdateFolderRequest = new UpdateFolderType();

FolderChangeType fcFolderchanges = new FolderChangeType();

FolderIdType cfFolderid = new FolderIdType();
cfFolderid.Id = cfCurrentFolder.FolderId.Id;
cfFolderid.ChangeKey = cfCurrentFolder.FolderId.ChangeKey;

fcFolderchanges.Item = cfFolderid;

SetFolderFieldType cpCalPerms = new SetFolderFieldType();
PathToUnindexedFieldType cpFieldURI = new PathToUnindexedFieldType();
cpFieldURI.FieldURI = UnindexedFieldURIType.folderPermissionSet;
cpCalPerms.Item = cpFieldURI;
cpCalPerms.Item1 = cfUpdateCalFolder;

fcFolderchanges.Updates = new FolderChangeDescriptionType[1] { cpCalPerms };
upUpdateFolderRequest.FolderChanges = new FolderChangeType[1] { fcFolderchanges };

UpdateFolderResponseType ufUpdateFolderResponse = esb.UpdateFolder(upUpdateFolderRequest);
if (ufUpdateFolderResponse.ResponseMessages.Items[0].ResponseClass == ResponseClassType.Success)
{
Console.WriteLine("Permissions Updated sucessfully");
}
else
{
// Handle Error

}

}

22 comments:

Viking said...

Hi

I have been looking for information on Folder Permittion but cant seem to find the right information.

What i am looking for is help with setting the default permission on Calendar to reviewer. So when you create a new mail user the Calendar permission has Reviewer permission from the go.

Can anybody help?

Shalldor

Glen said...

There is no default setting you can set that will change the permission on all and existing user. You will need to write some code to do this. The code in this post basically demonstrates how to do this.

You will need an understanding of programing and Exchange Web Service to make this work. If your after a scripted method have a look at something like http://gsexdev.blogspot.com/2005/05/changing-default-permissions-on.html this will still work on 2007 as long as you have rights to the mailboxes in question.

Cheers
Glen

Viking said...

Does that apply to changing the permission on the Default Calendar folder as well?

So if I want to change the permission on the Default Calender folder to have permission as "Default" = "Reviewer" so that when I create a new user that will be the folders permission I would need to do it through code?

Glen said...

Yes you need to make it part of your provisioning process eg create mailbox then connect to that mailbox and set the permission on that folder using a script or some code like demonstrated in this post

Cheers
Glen

trevor said...

What about if I'd like to change the default calendar permissions for EVERY mailbox on my Exchange 2007 server?

We'd like the default permissions for everyone to be Free/busy time,subject,location... What modifications would be needed to your code to make that functionality happen?

Thanks!
Trevor

Glen said...

Im trying to write a class library to make doing this easy from Powershell should be done it a couple of weeks.

Cheers
Glen

Trevor said...

A powershell script would be awesome. Could you send me an e-mail whenever you get this done? I'm not much of a coder, so I'd definately appreciate your work!

(trevor dot miller at rlicorp dot com)

Thanks!
Trevor

kun said...

hi.glen:

How can I change this folder permissions through Powershell
because EWS looks difficult for me

Glen said...

To Setting calendar permission using Powershell have a look at http://gsexdev.blogspot.com/2008/03/class-library-helper-for-setting.html

Cheers
Glen

Anonymous said...

Hi,

All the above discussion was around mailbox calendar folder.
Can you please post (or send link):
how to retrieve / set PermissionSet for public-folder?

Thanks,

Zachi.

Anonymous said...

Hi Glen,

how can I set the flag isVisible to false ? First I create a new permissionset with a default user and set IsVisible to false. Then I set these permissionset to a folder. If I open Outlook, the flag isvisible is set to true.

Can anybody help me ?

Erwin

Glen said...

Hi Erwin,

That should work okay what does your code look like. You would need to make sure that all the other permission setting dont give the user any rights. Are you doing this on a public folder ??. In Exchange SP1 there are EMS cmdlets that allow you to set client permission on public folders eg set-publicfolderclientpermissions which is another alternative to using EWS or Mapi

Cheers
Glen

Valerio said...

Thanks for you code. Has been very helpfull !!!
On MSDN I couldn't find anything userful.

Jorgen said...

Hi Glen, thanks for great posts! They are really helpful.
I have a question though, how can I via EWS find out a users permission on a folder? I need to get the permission on a folder for the logged in user, is that possible?

Many thanks in advance.
/jörgen.

Glen said...

see http://gsexdev.blogspot.com/2008/10/exchange-reverse-permission-audit.html. You can also use the new EWS managed API to do this as well.

Cheers
Glen

Jorgen said...

Thanks Glen!
Another thing... Is there a way in EWS to check if a specific user has the right to book a specific resource?

Many thanks in advance!
/jörgen.

borderline.barger said...

Glen,

I have been using your blog extensively and have one very late question this post.

One of earlier posters "edwin" stated that IsFolderVisible was not sticking as viewed from Outlook . I am having the same problem.

Currently I am calling the clear method on the Permissions collection and the apply the permissions that I need. There shoudl be only two users who can access it. An administrator and the user it is designed to help.

Anyway the folder remains visible to any user in Outlook though all of the other access permission are being applied.

Here is a code snippet.
public void SetUserPermissions(IGICXUser<_s> user, Folder folder)
{
folder.Permissions.Clear();
AddUserPermissionsTo__(user, folder);

foreach (var _u in _users)
{
if (_u.Email != null && _u.Email != user.Email && _u.Email != EmailAccount)
AddNotVisiblePermissions(_u, folder, false);
}
AddAdminPermissions(folder);
}

private void AddNotVisiblePermissions(IGICXUser<_s> user, Folder folder, bool visible)
{
var perms = new FolderPermission(user.Email, FolderPermissionLevel.None);
perms.IsFolderVisible = visible;
folder.Permissions.Add(perms);
folder.Update();
folder.Load();
}
Hope you see this. Thanks,

Ken

Glen said...

Try using the Custom permission type and setting each of the different properties this should allow you to set the visable property to the way you want.

Cheers
Glen

labhesh said...

Hi,
The strange behaviour
i have set the none permission on one of the folder for xyz user.
now when i try to retive the user permission it is retrived as custom persmission.
have u got this issue any time?

also other than xyz user i am also using user as default and anonymous permission.

The Dutch Wing said...

Hi,

Thank you for your very useful article.

What if you grant permissions to a group? I see a lot of examples of granting permissions to users, but seldom to groups. I found some vague references to using the SID, but can't seem to make it work.

Best regards,
Sebastian

Anonymous said...

Hi

I've been using this sample against Exchange 2010. And I wonder if you know if this is possible to achieve.
I have a public folder where the users are Contributors. Now one the users has left and I need to move his items to another user. Do you know what property on the items that decides who is the contributor?

Any help would be appreciated.

Thanks in advance
Peter

Anonymous said...

i'm raisinga question to the best of the best pshell guy means Glen

I’m facing a big issue since one week

can you help for this particular issue the deal is the following i should check in folder favourites under contacts in outlook if user toto has reviewer permission for 100 users if so do nothing if not add or modify existing permissions if not reviewer i do this with ews api but this cause me the issue that deleting all other existing user permission after folder.update() is applied you have an idea to deal with this issue ? part of my code that update the folder (currently delete the user and add again the rights


############################################################################################################################## if($existingperm -ne $null)
{ output("Removing existing permission to eici-phonedir on Contacts\Favourites")
$removal = $favouritesFolder.Permissions.Remove($existingperm)
output("Removed existing permission to eici-phonedir on Contacts\Favourites") }
$newfp = new-object Microsoft.Exchange.WebServices.Data.FolderPermission("eici-phonedir@europarl.europa.eu",$ReviewerPermission) $favouritesFolder.Permissions.Add($newfp) $favouritesFolder.Update()
output("Granted Reviewer permission to eici-phonedir on Contacts\Favourites") }