Skip to main content

Creating a new public folder and setting the permissions via EWS

I’ve had a couple of questions about this one based on a previous post that no-one really seemed to understand (oh and there was a bug in the code in post). Permissions aren't an easy subject and EWS doesn’t really give a straight forward method of manipulating ACL's but once you understand the basics its generally functional. It’s one thing you do need to dedicate some time too to get your logic right. I posted a calendar permissions helper for powershell a couple of months back I thought this would be a pretty simple task but when I started to test the library it ended up taking a numbers of hours to get the logic right. To summarize the things to watch out for when setting permission via EWS two important points are.
  • The first is that the ACE’s for the EWS security roles enumerations and Outlook roles don’t match. There are only sutle differences but if you need these roles to marry up in Outlook you need to include your own routines to do this.
  • When you want to modify,add or delete an ACE on a public folder (or a mailbox folder) do a GerFolder to retrieve the current ACL and make sure you build a new Permission set and populate it with the existing ACE’s and the add,or modified the ACE you want to change.

There’s a lot more detail you can go into but I think it just gets confusing as I would be just trying to repeat what I mentioned in the past but if you can understand those two points then this code will start making a little sense.

So the code basically creates a Subfolder under another subfolder under a Root Public folder. So the first part of the code is an enumeration section that first finds the root public folder and then traverses this Root folder to find the Subfolder which will be the parent of the new folder. It then creates a new folder and then after that it gets the permissions for the new folder and modifies them so that the default ACE has editor rights so all users can modify the contacts that are created in this folder. Adding or deleting ACE’s is pretty simple you just use a new PermissionType object. Well maybe simple once you’ve done it a few times.

I’ve put a download of the code here the code itself looks like

ExchangeServiceBinding esb = new ExchangeServiceBinding();
esb.RequestServerVersionValue = new RequestServerVersion();
esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007_SP1;
esb.Credentials = new NetworkCredential("username", "password","domain");
esb.Url = @"https://servername/EWS/Exchange.asmx";
DistinguishedFolderIdType parentFolder = new DistinguishedFolderIdType();
parentFolder.Id = DistinguishedFolderIdNameType.publicfoldersroot;
FolderIdType cfContactsFolder = FindFolder(esb, parentFolder, "ParentFolder", "Months");
CreateFolder(esb, cfContactsFolder, "Contacts-June");
GetContacts(esb, cfContactsFolder);
Console.WriteLine(cfContactsFolder.Id);
}
static FolderIdType FindFolder(ExchangeServiceBinding esb, DistinguishedFolderIdType fiFolderID, String pfRootFldName, String sfChildSub)
{
FolderIdType rvFolderID = new FolderIdType();
// Create the request and specify the travesal type
FindFolderType findFolderRequest = new FindFolderType();
findFolderRequest.Traversal = FolderQueryTraversalType.Shallow;

// Define the properties returned in the response
FolderResponseShapeType responseShape = new FolderResponseShapeType();
responseShape.BaseShape = DefaultShapeNamesType.Default;
findFolderRequest.FolderShape = responseShape;

// Identify which folders to search
DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];

folderIDArray[0] = new DistinguishedFolderIdType();
folderIDArray[0].Id = fiFolderID.Id;
// folderIDArray[0].ChangeKey = fiFolderID.ChangeKey;

//Add Restriction for DisplayName
RestrictionType ffRestriction = new RestrictionType();
IsEqualToType ieToType = new IsEqualToType();
PathToUnindexedFieldType diDisplayName = new PathToUnindexedFieldType();
diDisplayName.FieldURI = UnindexedFieldURIType.folderDisplayName;

FieldURIOrConstantType ciConstantType = new FieldURIOrConstantType();
ConstantValueType cvConstantValueType = new ConstantValueType();
cvConstantValueType.Value = pfRootFldName;
ciConstantType.Item = cvConstantValueType;
ieToType.Item = diDisplayName;
ieToType.FieldURIOrConstant = ciConstantType;
ffRestriction.Item = ieToType;
findFolderRequest.Restriction = ffRestriction;

// Add the folders to search to the request
findFolderRequest.ParentFolderIds = folderIDArray;
// Send the request and get the response
FindFolderResponseType findFolderResponse = esb.FindFolder(findFolderRequest);

// Get the response messages
ResponseMessageType[] rmta = findFolderResponse.ResponseMessages.Items;

foreach (ResponseMessageType rmt in rmta)
{
if (((FindFolderResponseMessageType)rmt).ResponseClass == ResponseClassType.Success)
{
FindFolderResponseMessageType ffResponse = (FindFolderResponseMessageType)rmt;
if (ffResponse.RootFolder.TotalItemsInView > 0)
{
foreach (BaseFolderType fld in ffResponse.RootFolder.Folders)
{
Console.WriteLine(fld.DisplayName.ToString());
if (fld.ChildFolderCount != 0)
{
rvFolderID = FindSubFolder(esb, fld, sfChildSub);
}
}


}
else
{ //handle no folder
}
}
else
{ //handle error
}

}
return rvFolderID;


}
static FolderIdType FindSubFolder(ExchangeServiceBinding esb, BaseFolderType pfParentFolder, String sfChildSub)
{
FolderIdType rvFolderID = new FolderIdType();
FolderType dd = new FolderType();
BaseFolderIdType bf = new FolderIdType();

// Create the request and specify the travesal type
FindFolderType findFolderRequest = new FindFolderType();
findFolderRequest.Traversal = FolderQueryTraversalType.Shallow;

// Define the properties returned in the response
FolderResponseShapeType responseShape = new FolderResponseShapeType();
responseShape.BaseShape = DefaultShapeNamesType.Default;
findFolderRequest.FolderShape = responseShape;

// Identify which folders to search
FolderIdType[] folderIDArray = new FolderIdType[1];

folderIDArray[0] = new FolderIdType();
folderIDArray[0] = pfParentFolder.FolderId;

// Add the folders to search to the request
findFolderRequest.ParentFolderIds = folderIDArray;
// Send the request and get the response
FindFolderResponseType findFolderResponse = esb.FindFolder(findFolderRequest);

// Get the response messages
ResponseMessageType[] rmta = findFolderResponse.ResponseMessages.Items;

foreach (ResponseMessageType rmt in rmta)
{
if (((FindFolderResponseMessageType)rmt).ResponseClass == ResponseClassType.Success)
{
FindFolderResponseMessageType ffResponse = (FindFolderResponseMessageType)rmt;
if (ffResponse.RootFolder.TotalItemsInView > 0)
{
foreach (BaseFolderType fld in ffResponse.RootFolder.Folders)
{
Console.WriteLine(fld.DisplayName.ToString());
if (fld.DisplayName == sfChildSub) { rvFolderID = fld.FolderId; };
if (fld.ChildFolderCount != 0 & rvFolderID.Id == null)
{
rvFolderID = FindSubFolder(esb, fld, sfChildSub);
}
}

}
else
{ //handle no folder
}
}
else
{ //handle error
}

}
return rvFolderID;


}
static void CreateFolder(ExchangeServiceBinding esb, FolderIdType pfParentFolder, String nfNewFolderName)
{
CreateFolderType cfCreateFolder = new CreateFolderType();
ContactsFolderType nfNewFolder = new ContactsFolderType();
nfNewFolder.DisplayName = nfNewFolderName;
TargetFolderIdType tfTargetFolder = new TargetFolderIdType();
cfCreateFolder.ParentFolderId = new TargetFolderIdType();
cfCreateFolder.ParentFolderId.Item = pfParentFolder;
cfCreateFolder.Folders = new ContactsFolderType[] { nfNewFolder };
CreateFolderResponseType cfResponse = esb.CreateFolder(cfCreateFolder);
FolderInfoResponseMessageType cfResponseMessage = (FolderInfoResponseMessageType)cfResponse.ResponseMessages.Items[0];
if (cfResponseMessage.ResponseClass == ResponseClassType.Success)
{
setPerms(esb, cfResponseMessage.Folders[0].FolderId);
}
else
{//handle Error }
}

}
static void setPerms(ExchangeServiceBinding esb, FolderIdType ffFolder) {

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

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


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

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

}
else
{//handle error
}

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

PermissionSetType cfCurrentPermsionsSet = cfCurrentFolder.PermissionSet;
PermissionSetType cfNewPermsionsSet = new PermissionSetType();
cfNewPermsionsSet.Permissions = new PermissionType[cfCurrentPermsionsSet.Permissions.Length];
for (int cpint = 0; cpint < distinguisheduser ="=" distinguisheduserspecified ="=" userid =" cfCurrentPermsionsSet.Permissions[cpint].UserId;" permissionlevel =" PermissionLevelType.Editor;" permissionlevel ="=" userid =" cfCurrentPermsionsSet.Permissions[cpint].UserId;" permissionlevel =" cfCurrentPermsionsSet.Permissions[cpint].PermissionLevel;" cfupdatefolder =" new" permissionset =" cfNewPermsionsSet;" upupdatefolderrequest =" new" fcfolderchanges =" new" cffolderid =" new" id =" cfCurrentFolder.FolderId.Id;" changekey =" cfCurrentFolder.FolderId.ChangeKey;" item =" cfFolderid;" cpperms =" new" cpfielduri =" new" fielduri =" UnindexedFieldURIType.folderPermissionSet;" item =" cpFieldURI;" item1 =" cfUpdateFolder;" updates =" new" folderchanges =" new" ufupdatefolderresponse =" esb.UpdateFolder(upUpdateFolderRequest);" responseclass ="=">

Popular posts from this blog

Export calendar Items to a CSV file using EWS and Powershell

Somebody asked about this last week and while I have a lot of EWS scripts that do access the Calendar I didn't have a simple example that just exported a list of the Calendar events with relevant information to a CSV file so here it is.

I've talked on this one before in this howto  but when you query the calendar folder using EWS you need to use a CalendarView which will expand any recurring appointments in a calendar. There are some limits when you use a calendarview in that you can only return a maximum of 2 years of appointments at a time and paging will limit the max number of items to 1000 per call. So if you have a calendar with a very large number of appointments you need to break your query into small date time blocks. In this example script I'm just grabbing the next 7 days of appointments if you want to query a longer period you need to adjust the following lines (keeping in mind what I just mentioned)

#Define Date to Query
$StartDate = (Get-Date)
$EndDate = (Ge…

EWS Managed API and Powershell How-To series Part 1

I thought I'd start the year with a series of posts that goes back over the basics of using the EWS Managed API from Powershell and provides a modular remarked example that you can easily cut and paste to build your own scripts. Along the way in this series I'll show a whole bunch of examples around specific things.

As a starting point for versions this will be Powershell Version 2.0  and the EWS Managed API 1.1 (which will soon change to 1.2 once released) http://www.microsoft.com/download/en/details.aspx?id=13480.

The starting point for any EWS script your going to write is connecting to Exchange for which there are three important pieces of information you will need. Firstly you need to know the version of Exchange your running in this script its going to be held in the following variable

$ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1

Other valid values for Exchange 2007 would be

$ExchangeVersion = [Microsoft.Exchange.WebServices.…

Writing a simple scripted process to download attachmentts in Exchange 2007/ 2010 using the EWS Managed API

Every complicated thing in life is made up of smaller simpler building blocks, when it comes to writing a script (or any code really) the more of these little building blocks you have to figure out the more the process of solving a problem can become bewildering. The Internet generally provides you with lots of half eaten sandwiches of information something someone else has taken a bite out but a lot of the time half done, and as with any code its usefulness declines over time as new and better API's and methods are derived. In this post I'm going to go through a simple scripted process that hopefully covers a few more of these smaller building blocks that you might face when asked to come up with a simple costless solution to perform an automated business function with a script.

So the process im going to look at is one that comes up a lot and that is you have an Email that comes into to certain mailbox every day with a certain subject in my case "Daily Export" this …
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.