Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, September 11, 2015

Moving a File to Another Site Collection, Using REST, High Trust App Only Permissions, AND in a Console Program - SharePoint 2013 On Premises

I know, I know, I'm an over achiever.  Here is the deal, I needed to move a bunch of files from one site collection to another.  Not a big deal, a pretty elementary task that I have done many times using the Client Side Object Model.  However, I knew that in the future I would need something similar to move files from a SharePoint hosted app to a Records Center site collection via Workflow or some other such method.  Since I like the REST API...  a lot...  I decided to take a whack at moving the file that way.
BUT, since I knew that I would need to create web services that would interact with SharePoint via REST or CSOM, as add-ins (Microsoft changed the name form Apps...) I wanted to use this authentication model for this task.

Program

With any program you need to start with requirements.  What do we want to do, and what limitations do we have.  I discussed some above.  

Here are our requirements for this program:

  • Move a file from a library to another library in a different site collection
  • Move the file's metadata, and add it to the fields of the new library
    • Title
  • Authenticate as a High Trust App
  • Use REST API
  • Program must be external to SharePoint
    • Console Application
Fun, right?

SharePoint Side

First things first.  I'm going to assume that you have Apps and High Trust Add-Ins already configured.  If you don't, you need to do that first.  I am also going to assume you know what the difference is between ACS and high trust Add-Ins.  You have to know the difference or your stuff won't work.  This is specifically for High Trust Add-Ins on an On Premises SharePoint 2013 deployment.  If you are attempting to do this to a SharePoint Online, you can, but you will need to change the way you register and authenticate your add-in.

Register Add-In

We start by registering an add-in.  This tells SharePoint that an Add-In exists and gives it an Add-In identity.  We will use this identity when we give permissions to the add-in and we use it to create access tokens in our program.  Again, this is a process that is well documented.  
All this process does is to register the add-in with the configuration database for this web application.  The web you do this in really doesn't matter.  Once an app is registered, the Client ID can be used to grant permissions anywhere in the Web Application.
What you need to focus on is when you click "generate" for your Client ID, make a note of it so that you can use it later on.  

The Client Secret I always click generate on too, just for kicks.  It is required for the form, but we don't need it.  The Title should be something descriptive for the accessing program, but is arbitrary.  I used "File Mover Program."  The App Domain again is needed for the form but not for our purposes.  I used the normal url for my Provider Hosted Add-Ins, apps.mydomain.com.  You can leave Redirect URL blank.  Make sure you have note of the Client ID!!!!!  Click Create.

Give Add-In Permissions

Now is the time on Sprockets where we give add-ins permission.  I just dated myself...  but I digress...  
Permissions are granted in two places, the source site needs READ permission, and the target site needs WRITE permission.  Because we are looking to do this in two separate site collections, it is best to grant access at the source and target web level.  That ensures that our add-in doesn't have more permissions that required.    This process MUST be done in each web that your add-in will be accessing, so that the web knows that the add-in has permission.
This is, yet again, a well documented process.  What is important here is that we add AllowAppOnlyPolicy="true" to our AppPermissionRequest node.  This tells the web that this add-in can work without having a user attached to it or, "Add-In only" permissions.  The kicker here is that we can't send a user with our access token request.  More on that later.  
In this case we grant the appropriate permissions as required.  

Console Program

Now that we have our Add-In registered and granted permissions, we are ready to code!!!
I use C# to write my programs in.  I'm a .NET guy and that is what I do.  You could, at this point, write the program in whatever language you want, but I don't want to.  Because I am using C#, I get to use a very handy class that Microsoft has created for .NET developers.  The TokenHelper class. 

Set up Project

Start by firing up Visual Studio (I'm using Visual Studio 2015) and creating a new C#, Windows, Classic Desktop project using the good old fashioned Console Application template.  Yay!!  Console Application programs ROCK!!
That is going to set up everything and create the handy dandy Program.cs class with the all familiar Main method.  Since I don't care about you judging me about my spaghetti code and not using OOP practices, everything goes in that method!  The good news is that it is only about  70 lines at most.

References

Next thing we do is set up the references that we are going to need.  Most of these are going to be used by the TokenHelper class, and not by our actual program.  Our program works almost completely with the references created Out Of the Box.  Because it is created to work in just about every situation, the TokenHelper needs lots of references.  Which brings us to the obvious question of, how do I get the TokenHelper class?  

Well..  It comes with the Visual Studio SharePoint App templates.  So... If you don't have one handy, you can create an empty Provider Hosted add-in and copy the code in the TokenHelper.  Then create a class in our Console Application called TokenHelper and paste the code in to that, or pick your favorite way to steal code and do that.  Whatever floats your boat.
The problem now is that you have a bunch of code that references assemblies that you don't have referenced in your program.  So reference the following:  Microsoft.Identity.Model, Microsoft.Identity.Model.Extensions, Microsoft.SharePoint.Client, and Microsoft.SharePoint.Runtime.  If I didn't get them all here, Visual Studio will yell at you and you can find out what you need by looking at the referenced assemblies in the provider hosted app as well as what you have in your program app.  
We are going to be making some HTTP calls and processing the responses so you are going to need to reference System.Web and System.Web.Extensions as well.
We want to use JSON as our data type, so use Nuget and download Newtonsoft.JSON as well.

App.config Configuration

Now we are ready to start...  sort of...  in your App.cofig file create a node called appSettings there we need to add the information the the TokenHelper uses to create the access tokens.  we need four key elements, ClientId, the ClientId that we got when we registered the app, the ClientSigningCertificationPath, the path to the certificate that you used to create the High Trust and the IssuerId for your High Trust environment.
These things are all very important, because if any of them are incorrect, you will not get an access token.

Program Code

Finally ready to code!  The code is very straight forward.

GET

1:   const string targetSiteCollectionUrl = "http://spalnnodom";  
2:   const string sourceSiteCollectionUrl = "http://spalnnodom/sites/contentorg2/";  
3:   Uri sourceSiteUri = new Uri(sourceSiteCollectionUrl);  
4:   Uri targetSiteUri = new Uri(targetSiteCollectionUrl);  
5:   //Get the access token for the URL.   
6:   //  Requires this app to be registered with the tenant. Null user identity aquires app only token. App must be registered for app only permissions.   
7:   //  For app + user credential is required    
9:    string sourceAccessToken = TokenHelper.GetS2SAccessTokenWithWindowsIdentity(sourceSiteUri, null);  
10:   string targetAccessToken = TokenHelper.GetS2SAccessTokenWithWindowsIdentity(targetSiteUri, null);  
11:  //Get source file as stream  
12:   string urlSourceFile = "http://spalnnodom/sites/contentorg2/_api/Web/GetFileByServerRelativeUrl('/sites/contentorg2/Records/SummaryEmails.docx')/$value";  
13:   HttpWebRequest fileRequest = (HttpWebRequest)HttpWebRequest.Create(urlSourceFile);  
14:    fileRequest.Method = "GET";  
16:    fileRequest.Accept = "application/json;odata=verbose";  
17:    fileRequest.Headers.Add("Authorization", "Bearer " + sourceAccessToken);  
18:    WebResponse webResponse = fileRequest.GetResponse();  
19:    Stream fileResponseStream = webResponse.GetResponseStream();  

We begin with adding two constants, our target and our source URLs.  We convert these to URIs and call the the TokenHelper.GetS2SAccessTokenWithWindowsIdentity method.
"NOW, JUST HOLD ON A DAMN MINUTE!!" you say "You said earlier that we were doing add-in only permissions.  Why in blue blazes are you calling a method with Windows Identity????"
You are very smart, you get a cookie.  This is one of those methods that the developer didn't think very hard when he wrote it, or maybe MSFT never wanted to show the world this method or... I don't know...  Anyway, the method is called GetS2SAccessTokenWithWindowsIdentity, however it is designed to be used weather you need add-in only access tokens or any other type of S2S access token.  How we get add-in only permissions is to pass in "null" as the windows user principal.  Goofy right?  That is the first "gotcha" of this process.
I create two access tokens, one for the source web and one for the target web.  Because, I have given the app different permissions in each web, I need two different acc

Next in the code, we format the URL that we will use in our HttpWebRequest to contact the SharePoint RESTful API.  Because we are looking for a file, we don't go to the list, we go to where files are stored according to SharePoint, the web.
Now, if you are an old-timer, like me, this makes perfect sense.  When we did development in the SharePoint Server Model, you got your SPFile objects from the SPWeb object and go to the "folder" that the file resides in, no muss no fuss.
However, if you are new to SharePoint, this URL bakes your noodle.  You look for the file in the web object, but you pass in the relative path that includes the library.  This all comes from the long and sorted history of SharePoint.  Just roll with it.  If you really want to conceptualize it, when you work with SharePoint files, think of the web as the root folder in a file structure, libraries are the next folder, and any SPFolder that you have in your library is the next folder in the hierarchy.  Since I don't have any other folders in my library, I use the root folder, the library URL.
One very important part of this URL is the very last part "/$value".  This part tells the SharePoint API to return the actual binary data of the file rather than the SPFile object.

The rest is what makes up a REST call to SharePoint 2013.  What should draw your attention is line 17.  Here is where we pass the OAuth token obtained from the TokenHelper class.  This is what will tell SharePoint that we are making the request as a registered app that is fully trusted.

After that, we use a Stream object to prepare the file binary to be moved to the new library.

Request Digest

Until now things have been easy.  Now we get tricky.  For a POST, SharePoint requires that we send two types of authentication.  One, we have already the AccessToken.  However, we need to use that access token to get a Request Digest token.  The Request Digest token is a client side token that is used to validate the client and prevent malicious attacks.  The token is unique to a user and a site and is only valid for a (configurable) limited time.
1: //Obtain FormDigest for upload POST  
2:  HttpWebRequest digestRequest = (HttpWebRequest)HttpWebRequest.Create("http://spalnnodom/_api/contextinfo");  
3:  digestRequest.Method = "POST";  
4:  digestRequest.Accept = "application/json;odata=verbose";  
5: //Authentication  
6:  digestRequest.Headers.Add("Authorization", "Bearer " + targetAccessToken);  
7: //ContentLength must be "0" for FormDigest Request  
8:  digestRequest.ContentLength = 0;  
9:  HttpWebResponse digestResponse = (HttpWebResponse)digestRequest.GetResponse();  
10: Stream webStream = digestResponse.GetResponseStream();  
11://Deseralize JSON object in the Response object. Uses Newtonsoft.Json.Net Nuget package  
12: StreamReader responseReader = new StreamReader(webStream);  
13: string newFormDigest = string.Empty;  
14: string response = responseReader.ReadToEnd();  
15: var j = JObject.Parse(response);  
16: var jObj = (JObject)JsonConvert.DeserializeObject(response);  
17: foreach (var item in jObj["d"].Children()) {  
18:  newFormDigest = item.First()["FormDigestValue"].ToString();  
19: }  
20: responseReader.Close();  
  
Again, we see the creation of a HttpWebRequest.  This we send to the TARGET web site to the special contextinfo action.  This action specifically returns the Request Digest token.  It is very similar to the GET we did earlier, the only difference is that we have a ContentLength of 0.  This is important.  You MUST have a ContentLength of 0 or you will get an error.
The only other interesting part of this is that we parse the response using the Newtonsoft.Json classes.  We didn't do this with the file because that came to us as an octet stream rather than a JSON object.

POST

Now we are finally ready to upload our file in to the target library.
1: //Upload file  
2:  string urlTargetFolder = "http://spalnnodom/_api/web/lists/getbytitle('Documents')/RootFolder/Files/add(url='MovedFileNameSCMove.docx',overwrite='true')";  
3:  HttpWebRequest uploadFile = (HttpWebRequest)HttpWebRequest.Create(urlTargetFolder);  
4:  uploadFile.Method = "POST";  
5:  uploadFile.Accept = "application/json;odata=verbose";  
6: //The content type must match the MIME type of the document  
7:  uploadFile.ContentType = "application/octet-stream";  
8:  uploadFile.Headers.Add("Authorization", "Bearer " + targetAccessToken);  
9:  uploadFile.Headers.Add("binaryStringRequestBody", "true");  
10: uploadFile.Headers.Add("X-RequestDigest", newFormDigest);  
11: Stream uploadStream = uploadFile.GetRequestStream();  
12: fileResponseStream.CopyTo(uploadStream);  
13: WebResponse uploadResponse = uploadFile.GetResponse();    

Pretty anticlimactic...  The only interesting thing here is that I actually do use the library to get the Root Folder, then use the Root Folder.Files.Add method to upload the file.

A gotcha that might getcha here is that you need to specify the MIME type of the document as the content type of the payload, and we must add an extra header of binaryStringRequestBody set to true, to tell the REST API that the the request payload is a binary stream, not a string.

Next you see the X-RequestDigest header that is set to the Request Digest string that we obtained earlier.
Finally, we use the HttpRequest GetReqestStream method with the Stream CopyTo method to upload our file using a stream rather than a bit array.  This should allow us to upload large files.

Then we get our uploadResponse that will come back as JSON representation of the SPFile object.  This is a good thing, because we will use that to get the list item that is associated with the file that we just uploaded.  We use that to update the file metadata.

Get the List Item

Getting the list item requires another REST call.  First we parse the data in the uploadRespose to find the ListItemAllFields URI property.  That will give us, among other things the URI of the list item, as well as the list item data type, something we will need when we do the POST that updates the list item.
1:  //Get list item  
2: //First get ListItemAllFields property from the response  
3:  Stream getItemAllFieldsStream = uploadResponse.GetResponseStream();  
4:  StreamReader getItemAllFieldsReader = new StreamReader(getItemAllFieldsStream);  
5:  string itemAllFieldsUri = string.Empty;  
6:  string itemAllFieldsResponse = getItemAllFieldsReader.ReadToEnd();  
7:  var iAllFields = JObject.Parse(itemAllFieldsResponse);  
8:  itemAllFieldsUri = iAllFields["d"]["ListItemAllFields"]["__deferred"]["uri"].ToString();  
9: //Get list item URI from response  
10: HttpWebRequest getListItemRequest = (HttpWebRequest)HttpWebRequest.Create(itemAllFieldsUri);  
11: getListItemRequest.Method = "GET";  
12: getListItemRequest.Accept = "application/json;odata=verbose";  
13: getListItemRequest.Headers.Add("Authorization", "Bearer " + targetAccessToken);  
14: WebResponse getListItemWebResponse = getListItemRequest.GetResponse();  
15: Stream getListItemResponseStream = getListItemWebResponse.GetResponseStream();  
16: StreamReader getListItemStreamReader = new StreamReader(getListItemResponseStream);  
17: string getListItemAllProperties = getListItemStreamReader.ReadToEnd();  
18: var getListItemJObject = JObject.Parse(getListItemAllProperties);  
19: string listItemUri = getListItemJObject["d"]["__metadata"]["uri"].ToString();        
20: string listItemDataType = getListItemJObject["d"]["__metadata"]["type"].ToString();  
This GET is the same as the GET before.  No need to go in to very far.  There are a couple of things to point out, though.  Take a look at the itemAllFieldsUri, listItemUri, and listItemDataType variables.
These variables show how you move through the JObjects in a JSON respnose using the Newtonsoft.Json classes.  In these cases I knew exactly what JSON values I wanted to use, and I navigated to them.
With this GET, we now have the list item URI associated with the file, and the list item data type.  We are ready to post our title change.

List Item MERGE 

Since we added a file to the library, we get a list item for free.  We have the URI of the list item, so we know we can create a REST call to update the metadata.  A required piece of the REST call to update list items is the list item data type.  We got this piece of data from the last GET so we are good to go for the final piece of the program:

1: //Update title Field    
2:  HttpWebRequest updateTitleRequest = (HttpWebRequest)HttpWebRequest.Create(listItemUri);  
3:  updateTitleRequest.Method = "POST";  
4:  updateTitleRequest.Accept = "application/json;odata=verbose";  
5:  updateTitleRequest.ContentType = "application/json;odata=verbose";  
6:  updateTitleRequest.Headers.Add("Authorization", "Bearer " + targetAccessToken);  
7:  updateTitleRequest.Headers.Add("X-RequestDigest", newFormDigest);  
8:  updateTitleRequest.Headers.Add("X-HTTP-Method", "MERGE");  
9:  updateTitleRequest.Headers.Add("IF-MATCH", "*");  
10: string payload = "{'__metadata':{'type':'" + listItemDataType + "'}, 'Title': 'Changed with REST!!'}";  
11: updateTitleRequest.ContentLength = payload.Length;  
12: StreamWriter updateItemWriter = new StreamWriter(updateTitleRequest.GetRequestStream());  
13: updateItemWriter.Write(payload);  
14: updateItemWriter.Flush();  
15: WebResponse updateTitleResponse = updateTitleRequest.GetResponse();  

Off we go...
For the most part it looks just like the post we did before.  Since this part of the program runs almost immediately after the file upload, one of the major advantages for using the REST API is that it is very fast, we can re-use our Request Digest token.

The headers that you should be aware of are the X-HTTP-Method and IF-MATCH headers.  Our Request Method is POST, because that is what we are doing, posting data to the server, however this is an update to an existing list item, so we need to let SharePoint know.  That is where the X-HTTP-Method comes in.  Many firewalls block anything other than GET or POST via HTTP traffic.  So we use this header for updates and deletes.

The IF-MATCH header makes the POST conditional.  Check here for an explanation.  Because we are saying this is an update to an existing entity, we want to ensure that if there isn't a matching entity, the POST will fail.

Finally we come to the payload string.  This is the JSON representation of the update object.
We first specify the type in the __metadata object, next we specify the column name to be updated, then the value of that column.  We put a length header to ensure proper formatting and security, then create a Stream to send the JSON home.
Execution happens with the GetResponse method.


THAT'S IT!!  Kind of a lot to go through, but a good bit of code to have.  I will be refactoring this in to a REST service to use with moving files in workflows.

Thanks to Andrew Connell.  He initially showed me the way with his GitHub post on how to connect to Office 365.  I have taken several classes with Andrew, and he is very free with answers to questions.

Tuesday, March 5, 2013

Modal Dialogs, ECMAScript, and Client/Server Interaction

I built a little Modal Dialog Application Page, launched by a Ribbon button, that would take what a user wrote in a text box and send it in an email to all of the "Assigned To"s in a task list.

My client wanted the ability to check the boxes next to the tasks, and have my Modal page send a message to just those users who were checked. Fairly simple, right? Not so much. You see, the ribbon button is controlled by SharePoint 2010's ECMA Script, where my "Notify" page is controlled by .NET managed code. So... How do we transfer JavaScript ECMA script to .NET managed code? It is fairly elementary to do through Silverlight's API, but what about simple JavaScript and .NET?

It takes a bit of cheating to get it done. First we need to look at how we launch a Modal Dialog Page. It is done in JavaScript. I am using a ribbon button to launch mine so the JavaScript is contained in the button's Custom Action elements file. Anyway, the modal dialog code involves creating calling the SP.UI.ModalDialog.showModalDialog method, and passing in the options that we want for the page. It looks like this:
var editOptions = SP.UI.$create_DialogOptions();
    editOptions.title = "Notify User";
    editOptions.url = "_layouts/SolutionFolder/Notify.aspx";
    editOptions.height = "600";
    editOptions.width = "500";
    editOptions.allowMaximize = "true";
    editOptions.showClose = "true";
    editOptions.args = args;
    editOptions.dialogReturnValueCallback = Function.createDelegate(null, CloseCallBack);
    SP.UI.ModalDialog.showModalDialog(editOptions);

Very straight forward. What we need to pay attention to here is the "args" option. This option allows us to pass objects from the originating script to the modal page. In my case, what I need is the ID if the SPList I am using and the individual IDs of the checked list items.

Fortunately, Microsoft has thought of that and we can obtain those very pieces of information straight away. We need only create a context and call two methods in the sp.js file. For the SPList ID, I call SP.ListOperation.Selection.getSelectedList() and for an array of the selected list item IDs I call SP.ListOperation.Selection.getSelectedItems(). Easy!
Next, I set those objects in to the options args object. It looks like this:
var context = SP.ClientContext.get_current();
var listId = SP.ListOperation.Selection.getSelectedList();
var items = SP.ListOperation.Selection.getSelectedItems();
var args = {
        listId: listId,
        items:  items
           };
This bit of code, of course, goes before you create the DialogOptions object.

Cool! Now I have my options, I launch my Notify.aspx page, and we are good! Not so fast! We still have to get the args object out of the JavaScript client world and in to the .NET server world. Now is where we get fancy.

In ASP.NET, how do we get information from the user on the client to the server managed code? We have some sort of a control that passes its user manipulated values to the back end via some sort of user action, like a button click. The same is true here. We create a generic "input" control on our page, and set the value of that control to be the args object. Yay!!

So, on our Modal Page we create a little bit of JavaScript. First, we call the ECMA Script method that will get the data we passed in the args object. We will then use JavaScript to set the value of our input control to be that of the args object.

First we need the input control:

Easy enough, right? Note the the runat is set to SERVER. This is very important. This control must be a SERVER control, otherwise we will not be able to get the value out. Microsoft has provided a pre-made method to get the args out, the SP.UI.ModalDialog.get_childDialog().get_args() method.
Now, inside a "script" tag on the modal page, we use the following JavaScript:
ExecuteOrDelayUntilScriptLoaded(function () {
            var args = SP.UI.ModalDialog.get_childDialog().get_args();
            document.getElementById('<%= args.ClientID %>').value = JSON.stringify(args);
        }, "sp.js")        

Notice here a couple of things. The entire bit of code is run in the ExecuteOrDelayUntilScriptLoaded delegate. That means that the entire page has to be loaded before you can star messing with any values. That means that the stuff we want from the SPList can not be gathered in the Page_Load method. You must wait until the page has been completely rendered!!!!
Second, you will notice the funky stuff in the document.getElementById function. This is because .NET will change the ID of all server controls. You need to know what the ID of the control is so that you can set the value, so... You have to call the managed code to get the ID. Yet another reason why you have to wait until the page is completely rendered before you can get to the args value.

This script, on the modal page, sets the value of the control. We are now able to get the args objects, but first we need to set up a couple of classes to format the data.

public class Args {
     public string ListId { get; set;}
     public System.Collections.Generic.List<Item> Items { get; set; }
}

public class Item {
     public int Id { get; set; }
}

Now we have some fun. We grab the args information then format it by using the System.Web.Script.Serialization.JavaScriptSerializer. It puts it in to a C# object format, integers for the integers and a string for the ID objects.

var javaScriptSerializer = new JavaScriptSerializer();
string json = args.Value;
var SelectedValues = javaScriptSerializer.Deserialize<Args>(json);

Now the SelectedValues object contains a string of the listID and a List of the item IDs. From these we can now plug in the values using a foreach loop in to the rest of the Notify code to send messages out to those items that were checked.

You can, of course, plug other simple objects in to the args object, just as long as there is some analogous type on the Managed side of the fence.

Tuesday, February 26, 2013

SPUser and Query-Based Distribution Lists

My current contract is with a company that decided after they installed Exchange 2003 that "if it ain't broke, don't fix it!!!!" So, they haven't updated Exchange in 10 years. It makes life harder in certain ECM and in Records Management situations, but for the most part it really doesn't affect me with my SharePoint work. Until the client wanted to get a task list created from every user in a very particular Distribution List...

First, what is a Query-Based Distribution List? In the Exchange 2003 world it is a security group that contains LDAP query objects, instead of the typical principal entities that normal groups contain. Now, it is a security group in name only. Because it does not contain actual entities, you can't use it to secure anything. You can only use it to email the users that are returned from the query or queries contained within. What makes it tricky is that the membership of the group is dynamic. The user list is created on the fly by the queries every time the group is called. Also, in Exchange 2003, there is no Exchange API that can be used to connect to these groups to resolve the members. Got all that? Good. Here we go!

First things first... In SharePoint if you are given a Security Group or a traditional Distribution List, how do you resolve the membership? Simple!! You need only call the SPUtility.GetPrincipalsInGroup method. That guy will return to you an array of SPPrincipalInfo objects which you can use to create SPUser objects in the manor of your choosing. My preference is to use the SPWeb.EnsureUser method. If the SPUser is not a member of the web or the group EnsureUser will add it and return the resolved SPUser object. If it IS a member it simply returns the SPUser object. It makes no difference if the group is a Distribution List or if the group is a Security Group. This method works for both.
public List<SPUser> GetUsersFromADGroup(string groupName, string groupDisplayName,  System.Collections.Generic.List<SPUser> masterList, SPWeb web) {
bool reachedMaxCount;
SPPrincipalInfo[] principalInfoArray = SPUtility.GetPrincipalsInGroup(web, groupName, int.MaxValue - 1, out reachedMaxCount);
if (principalInfoArray.Count() != 0) {
  foreach (SPPrincipalInfo info in principalInfoArray) {
    if (info.PrincipalType == SPPrincipalType.SecurityGroup || info.PrincipalType == SPPrincipalType.DistributionList) {
     GetUsersFromADGroup(info.LoginName, info.DisplayName,  masterList, web);
   } else {
      try {
       SPUser user = web.EnsureUser(info.LoginName);
        if (!masterList.Any(u => u.Name == user.Name)) {
         masterList.Add(user);
        }
     } catch {
        continue;
     }
   }
  }
  } else {
    GetUsersFromDynamicGroup(groupDisplayName, masterList, web);
  }
    return masterList;
}

A quick bit of code to show how you can get the SPRincipalInfo array using the SPUtility.GetPrincipalsInGroup method, then create SPUsers from that. The try/catch block is there in case there are any orphaned accounts sitting in the groups. These accounts can not be resolved, and will throw exceptions. You can choose to output these to an error list, or simply ignore them as I do here.


BUT, what about the Query-Based Distribution List(QBDL)? Since the QBDL has no actual members, remember the membership of the group is determined by LDAP query, the entities don't actually "belong" to the group, when you call the SPUtility.GetPrincipalsInGroup, you get a SPPrincipalInfo array with no objects. Bummer!

So, where do we go from here? We cannot directly get the group membership. So, have to come at this problem from a different angle. What if we had the LDAP query contained within the AD Query Object? If we had that, we could use .NET's System.DirectoryServices classes to execute it. Great!! So... where is that query held??
The one thing we know for sure about Microsoft Exchange is that they LOVE updating Active Directory Schema. They do it every time there is an update. Fortunately for us, anything that is added to the AD schema, we can very easily pull out and use.
First, you need to add a couple of references. You are going to need to reference System.DirectoryServices and System.DirectoryServices.AccountManagement. Add those guys to your using statements:

using System.DirectoryServices.AccountManagement;
using System.DirectoryServices;

After that we will be constructing the GetUsersFromDynamicGroup method that will be called should the SPPrincipalInfo array return with a count that is equal to 0. You can see the if up in the code, if (principalInfoArray.Count() != 0), and our method GetUsersFromDynamicGroup, being called in the "else" statement.

Now, what do we need to make everything happen. I first need the display name of the group. This is important, because the display name is how the methods in the System.DirectoryServices find the actual group. Why? Because that is how the object is named in LDAP. Note that the SPUtility.GetPrincipalsInGroup uses the login name of the group, NOT the display name. SPUtility.GetPrincipalsInGroup is looking for AD principals, NOT LDAP objects. These two concepts must be kept separate, or this process will not work (LDAP is looking for CN=GroupName,OU=OrgUnitName,DC=DomainName,DC=com, where a principal is looking for a name of DomainName\GroupLogInName).
After I have the display name, I am going to need all of the stuff to make a SPUser so I need the SPWeb object. Since I am returning everything as a List, I want to make sure that I am appending my SPUsers found in the QBDL to whatever else is in the group object, I include the existing List.

The first thing we are going to do in the method is set up a System.DirectoryServices.AccountManagement.PrincipalContext. Why? Well, I need to get a hold of the System.DirectoryServices.DirectoryEntry of the group. From that object, I can read what the members of the group are, and begin to resolve the users. Fortunately, getting the DirectoryEntry is very easy. I create a PrincipalContext using my domain name, then I create a GroupPrincipal using the PrincipalContext and the group display name. Now, it is just a matter of casting the return of the GroupPrincipal.GetUnderlyingObject method as a DirectoryEntry.
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, "DomainName");
GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(principalContext, IdentityType.Name, groupDisplayName);
DirectoryEntry group = (DirectoryEntry)groupPrincipal.GetUnderlyingObject();

After we have these objects ready to go, we are ready to start the heavy lifting. Now that we have the group as a DirectoryEntry, we can strip out the members of the group, in this case it will be the query objects. Since there really isn't a DirectoryEntry.Members property that will give us a nice DirectoryEntry.MembersCollection, we have to do that on our own. Luckily, we only need to cast the members property as IEnumerable. From there we can create our "foreach" loop and start our work.

object members = group.Invoke("Members", null);
foreach (object member in (IEnumerable)members) {
   //Do work in here
}

Here is where things get a little messy. We now have the Members as generic "objects." We really can't do anything with "objects." C# is a strongly typed language, so we need to transform this "object" in to something that has meaning. So, we need to create a new DirectoryEntry object. We then pass the member object to the DirectoryEntry constructor and, we automagically have a DirectoryEntry object from just a plain old "object." I have to admit here that I don't like using "objects." I like to strongly type everything so there is no confusion at design time or run time as to what objects are and how they can be used... But, because there is no MembersCollection object provided by the DirectoryEntry class, I couldn't figure out away to get the members and put them in a foreach loop. Sure, I could use some other loop, but... I am lazy and I didn't want to. You can make my code suck less and make your own cool loops. I didn't want to worry about it, so I punted and used "object."
Anyway, we have the member as a DirectoryEntry now. This member represents the query object that contains the LDAP query we need to actually resolve the users in the group. So, we can now finally call up the property that stores the LDAP query and execute it!! Yay!!

The property that concerns us is "msExchDynamicDLFilter." Essentially, all we need is that guy's value, and we are off to the next section of our code. Remember that all property objects are Dictionary objects. So you would retrieve the property value the exact same way you would any other dictionary value:
DirectoryEntry.Properties["msExchDynamicDLFilter"].Value.ToString().
Fun, right?

There is one other property that we need to get. Because we want to execute our LDAP query across the entirety of our domain forest, we want to grab the value of the msExchDynamicDLBaseDN property as well. With this guy we will construct the LDAP URI that we will use as our search base.

Now that we have our search base and our LDAP query we are ready to search AD for the members of the Dynamic group. .Net makes this very easy for us, because Microsoft has included a DirectorySearcher class that we can use to search AD. Intuitive, right? Actually it is:
  DirectoryEntry memberEntry = new DirectoryEntry(member);
  string ldapBase = memberEntry.Properties["msExchDynamicDLBaseDN"].Value.ToString();
  ldapBase = string.Format("LDAP://{0}", ldapBase);
  DirectoryEntry adRoot = new DirectoryEntry(ldapBase);
  DirectorySearcher search = new DirectorySearcher(adRoot, memberEntry.Properties["msExchDynamicDLFilter"].Value.ToString());
  SearchResultCollection results = search.FindAll();
 foreach (SearchResult result in results) {
//Create your SPUsers here
}

As you can see, we create the DirectorySearcher object using the the search base (adRoot), and the LDAP query (memberEntry.Properties["msExchDynamicDLFilter"].Value.ToString()). Microsoft provides us with a SearchResultCollection, nice of them, and all we need to do is call the FindAll method to populate it. There is also a FindOne method, if you are only looking for a single item. I'm looking for lots and lots, so I call FindAlll.
As with all of Microsoft's "collection" objects, the SearchResultsCollection inherits IEnumerable, so we can create a foreach loop using it.

Now it is just a matter of getting the property in the SearchResult object that contains the user's login name. After we have that, we need only call SPWeb.EnsureUser(loginName) and we are ready to add our SPUser object to the master List list. We do that the same way that we did it above:

 string loginName = string.Format("TRONOX\\{0}", result.Properties["samaccountname"].Value.ToString());
 try {
    SPUser user = web.EnsureUser(loginName);
    if (!masterList.Any(u => u.Name == user.Name)) {
      masterList.Add(user);
    }
} catch {
    continue;
}


You will notice that I do a little LINQ after calling EnsureUser and before I actually add the SPUser object to the List. I don't want any duplicates, so I check to see if there is a user already in the list with the same Name. If there isn't, I add it to the list. If there is, I ignore the object.

That is all there is to it!! It takes some getting around, but it is possible to get the membership of the QBDL!

Here are both of the methods that I was using in their entirety:

public List<SPUser> GetUsersFromADGroup(string groupName, string groupDisplayName,  System.Collections.Generic.List<SPUser> masterList, SPWeb web) {
 bool reachedMaxCount;
 SPPrincipalInfo[] principalInfoArray = SPUtility.GetPrincipalsInGroup(web, groupName, int.MaxValue - 1, out reachedMaxCount);
 if (principalInfoArray.Count() != 0) {
  foreach (SPPrincipalInfo info in principalInfoArray) {
    if (info.PrincipalType == SPPrincipalType.SecurityGroup || info.PrincipalType == SPPrincipalType.DistributionList) {
     GetUsersFromADGroup(info.LoginName, info.DisplayName,  masterList, web);
   } else {
      try {
       SPUser user = web.EnsureUser(info.LoginName);
        if (!masterList.Any(u => u.Name == user.Name)) {
         masterList.Add(user);
        }
     } catch {
        continue;
     }
   }
  }
  } else {
    GetUsersFromDynamicGroup(groupDisplayName, masterList, web);
  }
    return masterList;
}


public List<SPUser> GetUsersFromDynamicGroup(string groupDisplayName, List<SPUser> masterList, SPWeb web) {
 PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, "TRONOX");
 GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(principalContext, IdentityType.Name, groupDisplayName);
 DirectoryEntry group = (DirectoryEntry)groupPrincipal.GetUnderlyingObject();
 object members = group.Invoke("Members", null);
  foreach (object member in (IEnumerable)members) {
    DirectoryEntry memberEntry = new DirectoryEntry(member);
    string ldapBase = memberEntry.Properties["msExchDynamicDLBaseDN"].Value.ToString();
    ldapBase = string.Format("LDAP://{0}", ldapBase);
    DirectoryEntry adRoot = new DirectoryEntry(ldapBase);
    DirectorySearcher search = new DirectorySearcher(adRoot, memberEntry.Properties["msExchDynamicDLFilter"].Value.ToString());
    SearchResultCollection results = search.FindAll();
    foreach (SearchResult result in results) {
       string loginName = string.Format("TRONOX\\{0}", result.Properties["samaccountname"].Value.ToString());
       try {
          SPUser user = web.EnsureUser(loginName);
             if (!masterList.Any(u => u.Name == user.Name)) {
                masterList.Add(user);
             }
       } catch {
           continue;
       }
    }
  }
 return masterList;
}