Azure Active Directory Graph Client Library 1.0 – API Reference


Graph client library APIs can be categorized into Create, Query, Update, Delete and Other (custom actions) APIs.

Create

To create new object, set the required properties and use the “T Add<T>(GraphObject)” method. This method will return the object that is returned by the server (with the ObjectId and other server generated properties filled out). You cannot add any links as a part of Add or Update.

User userToBeAdded = new User(); 
userToBeAdded.DisplayName = “John Doe”; 
userToBeAdded.UserPrincipalName = userPrincipalName; 
userToBeAdded.AccountEnabled = true; 
userToBeAdded.MailNickname = userPrincipalName.Split(“@”.ToCharArray())[0]; 
userToBeAdded.PasswordProfile = new PasswordProfile(); 
userToBeAdded.PasswordProfile.Password = “P@ssw0rd!“; 
userToBeAdded.PasswordProfile.ForceChangePasswordNextLogin = false; 
userToBeAdded.UsageLocation = “US”;  
userToBeAdded = graphConnection.Add<User>(userToBeAdded);
 

Get object with the key (objectId)

ObjectId is the key for all graph objects. To get all the properties of an object

User retrievedUser = graphConnection.Get<User>(userObjectId);

Update

To update an object, set the properties that need to be changed and call the Update method. The library will submit only the properties that were modified. ObjectId is required to be able to update any object. You cannot manipulate any links as a part of Update.

User retrievedUser = graphConnection.Get<User>(userObjectId); 
retrievedUser.City = “Redmond”;  
retrievedUser = graphConnection.Update(retrievedUser);
 

Delete

To delete an object, use Delete method by passing in the object to be deleted.

graphConnection.Delete(retrievedUser);

List and Search graph objects

To List method allows you to query for the list of objects. Below is an example to get all the users in your tenant.

PagedResults<User> users = graphConnection.List<User>(null, null);

The PagedResults will contain the list of users that were returned by the request along with “PageToken” (to request for next page of results) and the “IsLastPage” property (which indicates the availability of further results). To get the next page of results, call List API with the same parameters, plus the page token.

users = graphConnection.List<User>(users.PageToken, null);
while (!pagedResults.IsLastPage)
{
 pagedResults = graphConnection.List<User>(users.PageToken, null);
// use pagedResults.Results
}

Method overrides

If you know the type of Graph object during compile time, you can use the template methods. If not, you can pass the type of the entity and you will get results of type GraphObject.

PagedResults<GraphObject> users = graphConnection.List(typeof(User), null, null);

Filters

Filters like ==, <=, >= and StartsWith are supported. For multi-valued properties, you can do the conditional “Any” expression on the
values. Filter conditions can be joined together using And / Or operators.

Helper methods are available to create each part of the filter expression and join them. You also have the option of using a custom generated filter expression (instead of using the helper methods).

FilterGenerator filter = new FilterGenerator();
filter.QueryFilter = ExpressionHelper.CreateConditionalExpression(typeof(User), GraphProperty.UserPrincipalName, userPrincipalName, ExpressionType.Equal);
PagedResults<User> pagedResults = graphConnection.List<User>(null, filter);

You can combine multiple search filters using the AND, OR operators.

BinaryExpression displayNameExpression = ExpressionHelper.CreateStartsWithExpression(typeof(User), GraphProperty.DisplayName, “ab”);
BinaryExpression cityExpression = ExpressionHelper.CreateEqualsExpression(typeof(User), GraphProperty.City, “Seattle”);
filters.QueryFilter = ExpressionHelper.JoinExpressions(displayNameExpression, cityExpression, ExpressionType.And);

Sorting

Using the filter generator, you can specify the property on which the results should be sorted. Currently, secondary sort order cannot be specified.

The server may not support sorting / filtering of some entities / properties.

Automatic expansion of links

When listing objects, you can optionally expand a link, by using the Expand property in the filter generator. Only one link can be expanded with each request.

FilterGenerator filterGenerator = new FilterGenerator();
filterGenerator.ExpandProperty = LinkProperty.Manager;
PagedResults<User> users = graphConnection.List<User>(null, filterGenerator);
 

Navigating Links

Links can be single-valued or multi-valued. When navigating the linked objects, the results are paged. Here is an example to get a page of linked objects.
PagedResults<GraphObject> members = graphConnection.GetLinkedObjects(group, LinkProperty.Members, null, -1);

There is a convenience method to page through all the linked objects. Please use it judiciously as the links can have a lot of members.

IList<GraphObject> members = graphConnection.GetAllDirectLinks(group, LinkProperty.Members);

Adding a link

To add an object to a multi-valued link or to set the value of a single valued property, you can use the AddLink method.

graphConnection.AddLink(group, user, LinkProperty.Members);

Deleting a link

To remove an object from a multi-valued link, you can use the DeleteLink method.

graphConnection.DeleteLink(group, user, LinkProperty.Members);

To remove an object from a single-valued link, you can use the DeleteLink method.

graphConnection.DeleteLink(user, null, LinkProperty.Manager);

Property serialization

The library uses json (minimal OData metadata) for all the requests. The client library has proxy classes for all the entities that are supported for the current server version. During deserialization, when the
client library encounters additional properties (like extensions), it stores the property values in a dictionary. The JSON string that was used to deserialize is also exposed through the library.

Error handling and exceptions

When errors are encountered, an exception of type GraphException or any of its sub-types will be thrown. By default, the client will retry the requests for certain types of exceptions (Internal Server Error).
The retry behavior is fully customizable. The exception object also contains all the response headers. If you log the exception object using the ToString() method, response headers and exception details will be printed.

try
{   
     PagedResults<GraphObject> members = graphConnection.GetLinkedObjects(group, LnkProperty.Members, null);
}
catch(GraphException graphException)
{  
     Console.WriteLine(graphException.ToString());
}

Renewing expired access tokens

When the request fails due to an expired access token, the AccessTokenExpiredException will be thrown. When you handle this exception, renew the access token, update the connection.AccessToken and retry your request.

Tracing graph requests

The library traces incoming / outgoing headers along with error/warning messages. You can add any .NET TraceListener to log these messages to a persistent store.

Mocking graph client library for unit tests

All public methods on GraphConnection class are made virtual so that they can be mocked easily. GraphConnection also has a protected override that can take in mock connection manager to make sure that the calls are not actually sent to the server.

 

API Reference

Public Constructors

public GraphConnection(string accessToken)

Description

Initializes a new instance of the GraphConnection class.

Parameters

accessToken – Access token obtained for the current user/application using Active Directory Authentication Library or directly calling Microsoft Access Control Service.

Return value

NA

Exceptions

ArgumentNullException if accessToken is null.

ArgumentException if accessToken is not well formed.

Remarks

Creating a new GraphConnection does not result in a new SSL connection. The graph client library creates a new HttpWebRequest before making any request and disposes it immediately.

 

public GraphConnection(string accessToken, GraphSettings graphSettings)

Description

Initializes a new instance of the GraphConnection class, using the settings provided.

Parameters

accessToken – Access token obtained for the current user/application using Active Directory Authentication Library or directly calling Microsoft Access Control Service.

graphSettings – An instance of GraphSettings containing override properties for various properties like retry logic, api-version and graph domain name.

Exceptions

ArgumentNullException if accessToken is null.

ArgumentException if accessToken is not well formed.

 Remarks

Creating a new GraphConnection does not result in a new SSL connection. The graph client library creates a new HttpWebRequest before making any request and disposes it immediately.

 

public GraphConnection(string accessToken, Gud clientRequestId, GraphSettings graphSettings)

Description

Initializes a new instance of the GraphConnection class, using the settings provided and the client request id.

Parameters

accessToken – Access token obtained for the current user/application using Active  Directory Authentication Library or directly calling Microsoft Access Control Service.

clientRequestId – Client request identifier sent to the server along with the request that uniquely identifies the request.

graphSettings – An instance of GraphSettings containing override properties for various properties like retry logic, api-version and graph domain name.

Exceptions

ArgumentNullException if accessToken is null.

ArgumentException if accessToken is not well formed.

 Remarks

 Creating a new GraphConnection does not result in a new SSL connection. The graph client library creates a new HttpWebRequest before making any request and disposes it immediately.

 

Public Methods

public virtual TenantDetail GetTenantDetails()

Description

Gets the details of the company for the tenant associated with the accessToken.

Parameters

None

Return value

TenantDetail containing the information of the company.

Exceptions

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

GraphException if there were any network issues or if the service did not provide a valid response.

 

public virtual PagedResults<GraphObject> List(Type objectType, string pageToken, FilterGenerator filter)

Description

Gets a page of graph objects matching the type and filter.

Parameters

objectType – Type of the requested graph objects.

pageToken – null to get the first page, PagedResults.PageToken from the previous page to the next page.

filter – null to get all the results, a valid FilterGenerator to filter on specific properties or expand specific properties.

Return value

PagedResults containing the requested page along with the pageToken to be used for getting next page, if next page is available.

Exceptions

ArgumentNullException if objectType is null.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

PageNotAvailableException if pageToken has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

UnsupportedQueryException if the filter provided is not supported by the server.

GraphException if there were any network issues or if the service did not provide a valid response.

 

public virtual PagedResults<T> List<T>(string pageToken, FilterGenerator filter)

Description

Override method to list the graph objects that match the filter.

Parameters

pageToken – null to get the first page, PagedResults.PageToken from the previous page to the next page.

filter – null to get all the results, a valid FilterGenerator to filter on specific properties or expand specific properties.

Return value

PagedResults containing the requested page along with the pageToken to be used for getting next page, if next page is available.

Exceptions

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

PageNotAvailableException if pageToken has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

UnsupportedQueryException if the filter provided is not supported by the server.

GraphException if there were any network issues or if the service did not provide a valid response.

 

public virtual T Get<T>(string objectId)

Description

Gets an object of given type identified by the unique objectId.

Parameters

objectId – Unique object identifier set by the server when the graph object was created.

Return value

The requested graph object.

Exceptions

ArgumentNullException if the given objectId is null or empty.

ObjectNotFoundException if no graph object exists with the given objecId.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

GraphException if there were any network issues or if the service did not provide a valid response.

 

public virtual GraphObject Get(Type objectType, string objectId)

Description

Overload that is to be used when the object type is not known at the compile time.

Parameters

objectType – Type of the graph object.

objectId – Unique object identifier set by the server when the graph object is created.

Return value

The requested graph object.

Exceptions

ArgumentNullException if the given objectType or objectId is null or empty.

ObjectNotFoundException if no graph object exists with the given objecId.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

GraphException if there were any network issues or if the service did not provide a valid response.

 

public virtual T Add<T>(T graphObject)

Description

Creates the given object in graph.

Parameters

graphObject – A graph object with required properties.

Return value

Created object returned by the server.

Exceptions

ArgumentNullException if the given graphObject is null.

ArgumentException if given graph object is not supported for creation.

BadRequestException if any of the values set on the graph object are invalid.

DuplicateObjectException if a graph object already exists with same unique identifier.

PropertyValidationException if any of the required properties are not set on graph object.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

QuotaExceededException if number of objects exceeded the limit set by the server. Please contact Microsoft support.

GraphException if there were any network issues or if the service did not provide a valid response.

 

public virtual GraphObject Add(Type objectType, GraphObject graphObject)

Description

Overload for creating the graph object when the type is not known during compile time.

Parameters

objectType – Type of the graph object.

graphObject – A graph object with required properties.

Return value

Created object returned by the server.

Exceptions

ArgumentNullException if the given objectType or graphObject is null.

ArgumentException if given graph object is not supported for creation.

BadRequestException if any of the values set on the graph object are invalid.

DuplicateObjectException if a graph object already exists with same unique identifier.

PropertyValidationException if any of the required properties are not set on graph object.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

QuotaExceededException if number of objects exceeded the limit set by the server. Please contact Microsoft support.

GraphException if there were any network issues or if the service did not provide a valid response.

 

public virtual T Update<T>(T graphObject)

Description

Updates the given object using the graph api.

Parameters

graphObject – A graph object with any changed properties. Only changed properties are sent to the server.

Return value

Updated object returned by the server.

Exceptions

ArgumentNullException if the given graphObject is null.

BadRequestException if any of the values set on the graph object are invalid.

DuplicateObjectException if a graph object already exists with same unique identifier.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

QuotaExceededException if number of objects exceeded the limit set by the server. Please contact Microsoft support.

ObjectNotFoundException if the object being updated was not found.

PropertyValidationException if there is a syntax violation with the property being updated.

GraphException if there were any network issues or if the service did not provide a valid response.

 

public virtual GraphObject Update(GraphObject graphObject)

Description

Updates the given object using the graph api.

Parameters

graphObject – A graph object with any changed properties. Only changed properties are sent to the server.

Return value

Updated object returned by the server.

Exceptions

ArgumentNullException if the given graphObject is null.

BadRequestException if any of the values set on the graph object are not allowed.

DuplicateObjectException if a graph object already exists with same unique identifier.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

QuotaExceededException if number of objects exceeded the limit set by the server. Please contact Microsoft support.

ObjectNotFoundException if the object being updated was not found.

PropertyValidationException if there is a syntax violation with the property being updated.

GraphException if there were any network issues or if the service did not provide a valid response.

 

public virtual void Delete(GraphObject graphObject)

Description

Deletes the given object using the graph api.

Parameters

graphObject – A graph object with unique object identifier.

Return value

None

Exceptions

ArgumentNullException if the given graphObject is null.

ObjectNotFoundException if the graph object does not exit.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

QuotaExceededException if number of objects exceeded the limit set by the server. Please contact Microsoft support.

BadRequestException if DELETE is not supported on this entity.

GraphException if there were any network issues or if the service did not provide a valid response.

 

public virtual PagedResults<GraphObject> GetLinkedObjects(GraphObject graphObject, LinkProperty linkProperty, string nextPageToken)

Description

Gets a page of linked objects of a graph object given the link name.

Parameters

graphObject – Graph object that contains links.

linkProperty – Link property name (Manager, Members, etc.,)

nextPageToken – null to request for first page, a valid PageToken from a previous PagedResults.PageToken to request for a next page.

Return value

PagedResults containing the requested page along with the pageToken to be used for getting next page, if next page is available.

Exceptions

ArgumentNullException if graphObject is null.

ArgumentExecption if the given linkProperty is not supported on the given graphObject.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

PageNotAvailableException if pageToken has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

 

public virtual PagedResults<GraphObject> GetLinkedObjects(GraphObject graphObject, LinkProperty linkProperty, string nextPageToken, int top)

Description

Overload for getting linked objects to request for specific number of results in the page specified by “top”.

Parameters

graphObject – Graph object that contains links.

linkProperty – Link property name (Manager, Members, etc.,)

nextPageToken – null to request for first page, a valid PageToken from a previous PagedResults.PageToken to request for a next page.

Top – Number of values to be returned by the server.

Return value

PagedResults containing the requested page along with the pageToken to be used for getting next page, if next page is available.

Exceptions

ArgumentNullException if graphObject is null.

ArgumentExecption if the given linkProperty is not supported on the given graphObject.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

PageNotAvailableException if pageToken has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

 

public virtual IList<GraphObject> GetAllDirectLinks(GraphObject graphObject, LinkProperty linkProperty)

Description

Gets all pages of linked objects of a graph object given the link name. If multiple pages exist, the call will enumerate through all the pages.

Parameters

graphObject – Graph object that contains links.

linkProperty – Link property name (Manager, Members, etc.,)

Return value

List containing all the linked objects.

Exceptions

ArgumentNullException if graphObject is null.

ArgumentExecption if the given linkProperty is not supported on the given graphObject.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

 

public virtual void AddLink(GraphObject sourceObject, GraphObject targetObject, LinkProperty linkProperty)

Description

Adds a link specified by the linkProperty between the source and the target graph objects

Parameters

sourceObject – Source graph object.

targetObject – Target graph object.

linkProperty – Link property name (Manager, Members, etc.,)

Return value

None.

Exceptions

ArgumentNullException if sourceObject or targetObject are null.

ArgumentExecption if the given linkProperty is not supported between source object and target object.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

 

public virtual void DeleteLink(GraphObject sourceObject, GraphObject targetObject, LinkProperty
linkProperty)

Description

Deletes a link specified by the linkProperty between the source and the target graph objects

Parameters

sourceObject – Source graph object.

targetObject – Target graph object.

linkProperty – Link property name (Manager, Members, etc.,)

Return value

None.

Exceptions

ArgumentNullException if sourceObject or targetObject are null.

ArgumentExecption if the given linkProperty is not supported between source object and target object.

ObjectNotFoundException if the given link does not exist between source object and target object.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

 

public virtual Stream GetStreamProperty(GraphObject graphObject, GraphProperty graphProperty, string acceptType)

Description

Gets a stream property specified by graphProperty on a given graph object.

Parameters

graphObject – Graph object on which stream property needs to be obtained.

graphProperty – Name of stream property

acceptType – Stream type to be specified for ContentType header (like image/jpeg, image/gif, etc.,)

Return value

MemoryStream representing the obtained stream.

Exceptions

ArgumentNullException if graphObject or acceptType are null.

ArgumentExecption if the given graphProperty is not supported on the graph object.

BadRequestException if the acceptType is invalid.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

 

public virtual void SetStreamProperty(GraphObject graphObject, GraphProperty graphProperty, MemoryStream stream, string acceptType)

Description

Sets a stream property specified by graphProperty on a given graph object.

Parameters

graphObject – Graph object on which stream property needs to be obtained.

graphProperty – Name of stream property.

stream – Stream to be set on the graph object.

acceptType – Stream type to be specified for ContentType header (like image/jpeg, image/gif, etc.,)

Return value

None

Exceptions

ArgumentNullException if graphObject or acceptType are null.

ArgumentExecption if the given graphProperty is not supported on the graph object.

BadRequestException if the acceptType is invalid.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

 

public virtual IList<BatchResponseItem> ExecuteBatch(params Expression<Action>[] batchRequests)

Description

Executes a list of graph methods in a single batch. All the requests are sent to the server in a single batch request and the response for each request is returned in a separate batch response item.

Parameters

batchRequests – One or more graph methods. 

Return value

List of responses, one for each of the batch request sent.

Exceptions

ArgumentExecption if the batchRequests is null or number of requests is more than 5.

BadRequestException if any of the requests is invalid.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

 

public virtual IList<BatchResponseItem> ExecuteBatch(IList<BatchRequestItem> batchRequests)

Description

Overload for executing batch requests if the requests are manually built using BatchRequestItem. All the requests are sent to the server in a single batch request and the response for each request is returned in a separate batch response item.

Parameters

batchRequests – One or more graph batch requests. 

Return value

List of responses, one for each of the batch request sent.

Exceptions

ArgumentExecption if the batchRequests is null or number of requests is more than 5.

BadRequestException if any of the requests is invalid.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

 

public virtual T GetContainment<T>(GraphObject parent, string containmentObjectId)

Description

Gets a containment object of given type identified by the unique objectId and the parent.

Parameters

parent – The parent object of the containment object.

containmentObjectId – Unique object identifier set by the server when the graph object was created.

Return value

The requested graph containment object.

Exceptions

ArgumentNullException if the given objectId is null or empty.

ObjectNotFoundException if no graph object exists with the given containmentObjectId or if the parent object does not exist.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

GraphException if there were any network issues or if the service did not provide a valid response.

 

public virtual GraphObject GetContainment(GraphObject parent, Type objectType, string containmentObjectId)

Description

Overload that is to be used when the object type is not known at the compile time for getting a containment object.

Parameters

parent – The parent object of the containment object.

objectType – Type of the graph object.

containmentObjectId – Unique object identifier set by the server when the graph object is created.

Return value

The requested graph containment object.

Exceptions

ArgumentNullException if the given objectType or objectId is null or empty.

ObjectNotFoundException if no graph object exists with the given containmentObjectId or if the parent object does not exist.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

GraphException if there were any network issues or if the service did not provide a valid response.

 

public virtual T AddContainment<T>(GraphObject parent, T containmentObject)

Description

Creates the given containment object in graph.

Parameters

parent – The parent object of the containment object.

containmentObject – A graph object with required properties.

Return value

Created object returned by the server.

Exceptions

ArgumentNullException if the given graphObject is null.

ArgumentException if given graph object is not supported for creation.

BadRequestException if any of the values set on the graph object are invalid.

DuplicateObjectException if a graph object already exists with same unique identifier.

PropertyValidationException if any of the required properties are not set on graph object.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

QuotaExceededException if number of objects exceeded the limit set by the server. Please contact Microsoft support.

GraphException if there were any network issues or if the service did not provide a valid response.

 

public virtual GraphObject AddContainment(GraphObject parent, GraphObject containmentObject)

Description

Creates the given containment object in graph.

Parameters

parent – The parent object of the containment object.

containmentObject – A graph object with required properties..

Return value

Created object returned by the server.

Exceptions

ArgumentNullException if the given objectType or graphObject is null.

ArgumentException if given graph object is not supported for creation.

BadRequestException if any of the values set on the graph object are invalid.

DuplicateObjectException if a graph object already exists with same unique identifier.

PropertyValidationException if any of the required properties are not set on graph object.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

QuotaExceededException if number of objects exceeded the limit set by the server. Please contact Microsoft support.

GraphException if there were any network issues or if the service did not provide a valid response.

 

public virtual T UpdateContainment<T>(GraphObject parentObject, T containmentObject)

Description

Updates the given containment object using the graph api.

Parameters

parent – The parent object of the containment object.

containmentObject – A graph object with required properties..

Return value

Updated object returned by the server.

Exceptions

ArgumentNullException if the given graphObject is null.

BadRequestException if any of the values set on the graph object are invalid.

DuplicateObjectException if a graph object already exists with same unique identifier.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

QuotaExceededException if number of objects exceeded the limit set by the server. Please contact Microsoft support.

ObjectNotFoundException if the object being updated was not found.

PropertyValidationException if there is a syntax violation with the property being updated.

GraphException if there were any network issues or if the service did not provide a valid response.

 

public virtual void DeleteContainment(GraphObject containmentObject)

Description

Deletes the given containment object using the graph api.

Parameters

parent – The parent object of the containment object.

containmentObject – A graph object with unique object identifier.

Return value

None

Exceptions

ArgumentNullException if the given graphObject is null.

ObjectNotFoundException if the graph object does not exit.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

QuotaExceededException if number of objects exceeded the limit set by the server. Please contact Microsoft support.

BadRequestException if DELETE is not supported on this entity.

GraphException if there were any network issues or if the service did not provide a valid response.

 

public virtual PagedResults<GraphObject> ListContainments(GraphObject parent, Type containmentType, string pageToken, FilterGenerator filter)

Description

Gets a page of graph containment objects on a given parent, matching the type and filter.

Parameters

parent – The parent object of the containment object.

containmentType – Type of the requested graph objects.

pageToken – null to get the first page, PagedResults.PageToken from the previous page to the next page.

filter – null to get all the results, a valid FilterGenerator to filter on specific properties or expand specific properties.

Return value

PagedResults containing the requested page along with the pageToken to be used for getting next page, if next page is available.

Exceptions

ArgumentNullException if objectType is null.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

PageNotAvailableException if pageToken has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

UnsupportedQueryException if the filter provided is not supported by the server.

GraphException if there were any network issues or if the service did not provide a valid response.

 

public virtual PagedResults<T> ListContainments<T>(GraphObject parent, string pageToken, FilterGenerator filter)

Description

Override method to list the graph containment objects on a given parent that match the filter.

Parameters

parent – The parent object of the containment object.

pageToken – null to get the first page, PagedResults.PageToken from the previous page to the next page.

filter – null to get all the results, a valid FilterGenerator to filter on specific properties or expand specific properties.

Return value

PagedResults containing the requested page along with the pageToken to be used for getting next page, if next page is available.

Exceptions

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

PageNotAvailableException if pageToken has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

UnsupportedQueryException if the filter provided is not supported by the server.

GraphException if there were any network issues or if the service did not provide a valid response.

 

public virtual IList<string> GetMemberGroups(User user, bool securityEnabledOnly)

Description

Returns list of object identifiers of the groups that the given user is member of directly or transitively.

Parameters

user – User whose groups need to be returned.

securityEnabledOnly – Returns only security groups if set to true, otherwise returns all groups.

Return value

List of object identifiers of groups that the user is member of.

Exceptions

ArgumentNullExecption if the given user is null.

ArgumentException if object identifier of the user is not set.

ObjectNotFoundException if the given user does not exist.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

 

public virtual IList<string> CheckMemberGroups(GraphObject graphObject, IList<string> groupIds)

Description

Verifies if a given graph object is a member of given list of groups, returns a subset of groups it is member of.

Parameters

graphObject – Graph object whose groups need to be checked.

groupIds – List of groups identified by the unique object identifiers.

Return value

Subset of list of object identifiers of groups that the graph object is member of

Exceptions

ArgumentNullExecption if the given graph object or list of groupIds is null.

ArgumentException if object identifier of the graph object is not set.

ObjectNotFoundException if the given graph object does not exist.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

 

public virtual Application Restore(Application application, IList<string> identifierUris)

Description

Restores a soft deleted Application object and adds the given list of identifierUris to it.

Parameters

Application – Application that needs to be restored.

identifierUris – List of identifier URIs that need to be added to the application.

Return value

Restored application.

Exceptions

ArgumentNullExecption if the given application object is null.

ArgumentException if object identifier of the application is not set.

ObjectNotFoundException if the given application does not exist.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

 

public virtual User AssignLicense(User user, IList<AssignedLicense> addLicenses, IList<Guid> removeLicenses)

Description

Adds/removes the licenses on a given user.

Parameters

user – User whose licenses needs to be managed.

addLicenses – List of licenses to be assigned to the user.

removeLicenses – Lise of licenses to be removed from the user.

Return value

Updated user after adding/removing the licenses.

Exceptions

ArgumentNullExecption if the given user object is null.

ArgumentException if object identifier of the user is not set.

ObjectNotFoundException if the given user does not exist.

BadRequestException if any of the given licenses to be added or removed are invalid.

AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

 

public virtual bool IsMemberOf(string groupId, string memberId)

Description

Verifies if a given member is a member of given group.

Parameters

groupId – Unique object identifier of the given group.

memberId – Unique object identifier of the given graph object.

Return value

True if the member is part of the group member, false otherwise.

Exceptions

ArgumentNullExecption if the given groupId or memberId is null.

ObjectNotFoundException if the given group or member does not exist.AuthenticationException if accessToken provided as a part of GraphConnection is not valid.

ExpiredTokenException if accessToken provided as a part of GraphConnection has expired.

RequestThrottledException if number of calls has exceeded the throttle limit set by the server.

 

Comments (23)

  1. Silvia Giovetti says:

    Is it possible to generate a filter using an expression without using ExpressionHelper object ?

    If yes can you show me an example ?

    The idea is to read the filter from a config file (for example filter= "property1 eq value1", or filter= "property1 eq value1 and property2 eq value2")

    Thanks in advance

  2. Pavan Kompelli - MSFT says:

    Hi Silvia, You can use the FilterGenerator.OverrideQueryFilter to pass a OData compliant filter directly. For example you could say –

    FilterGenerator filter = new FilterGenerator();

    filter.OverrideQueryFilter = "displayName eq 'Adam'";

    PagedResults<User> pagedUserResults = graphConnection.List<User>(null, filter);

  3. SilviaG says:

    It Works ! Thanks !!

  4. Yvan Duhamel says:

    I'm trying to get properties of GraphObject (User and Group) like this:

    User myUser;

    myUser.UserPrincipalName // returns UPN

    GraphObject graphObj = (graphObj) myUser;

    GraphObject["UserPrincipalName"] // returns null instead of the UPN

    I really need to get the UPN this way.

    Using debugger I can see that graphObj.PropertiesMaterializedFromDeserialization has 27 properties but graphObj.NonSerializedProperties has 0, and I see that "GraphObject[propertyName]" searches in NonSerializedProperties.

    Can you please help me to achieve this?

    Many thanks for your help.

  5. Yvan Duhamel says:

    [EDIT: fix typo in my previous post]

    I'm trying to get properties of GraphObject (User and Group) like this:


    User myUser;

    myUser.UserPrincipalName // returns UPN

    GraphObject graphObj = (graphObj) myUser;

    graphObj["UserPrincipalName"] // returns null instead of the UPN


    I really need to get the UPN this way.

    Using debugger I can see that graphObj.PropertiesMaterializedFromDeserialization has 27 properties but graphObj.NonSerializedProperties has 0, and I see that "graphObj[propertyName]" searches in NonSerializedProperties.

    Can you please help me to achieve this?

    Many thanks for your help.

  6. Erik Fjellanger Schmidt says:

    Trying to make a REST call through SharePoint's SP.WebRequestInfo.

    I'm getting the error "The remote server returned the following error while establishing a connection – 'Unauthorized'." trying to call https://graph.windows.net/[Client]/users?api-version=2013-11-0.

    I've successfully retrieved a access token.

    Can you help me out why i'm getting this error?

    Here is the code i'm using:

    var url = "graph.windows.net/…/users

               var context = SP.ClientContext.get_current();

               var request = new SP.WebRequestInfo();

               request.set_url(url);

               request.set_method("GET");

               request.set_headers({

                   "Authorization": token.token_type + " " + token.access_token,

                   "Content-Type": "application/json"

               });

               var response = SP.WebProxy.invoke(context, request);

               context.executeQueryAsync(successHandler, errorHandler);

               function successHandler() {

                   if (response.get_statusCode() == 200) {

                       var responseBody = JSON.parse(response.get_body());

                       deferred.resolve(responseBody);

                   } else {

                       var httpCode = response.get_statusCode();

                       var httpText = response.get_body();

                       deferred.reject(httpCode + ": " + httpText);

                   }

               }  

  7. Pavan Kompelli - MSFT says:

    Yvan,

    We have upgrade the nuget package with the fix (1.0.3). You should able to query using GraphObject["userPrincipalName"] now. Please note that the name of the property should be the actual name in the $metadata (json property name).

  8. Pavan Kompelli - MSFT says:

    Erik,

    Can you please share the entire response (with the headers) for the failure? It looks like the token you obtained is not for graph.windows.net.

  9. Yvan Duhamel says:

    Hello Pavan, great! I will take a look.

    Besides, do you plan to release a version that does not require an assemblyBinding for Newtonsoft.Json?

    I'm using this API in SharePoint and that's a huge pain since it forces to add assemblyBinding in machine.config on every server in the farm.

    It cannot be easily done at higher level (like aspnet.config or web.config) because there are so many processes involved that only machine.config covers all of them.

  10. Joe says:

    FYI this is an great error message the REST api can return.

    "{"lang":"en","value":"One or more properties contains invalid values."}"

    It should be changed to:

    "One or more properties contains invalid values. Please debug via the only available option. Stop, comment out code, try again. Repeat for each property until this message goes away and waste your entire day"

  11. Tom Laird-McConnell says:

    Super disappointed there are no async methods in this library… 🙁 🙁 🙁

  12. Howard van Rooijen says:

    Are there any plans to add async support to the library?

  13. Robert Ward - MSFT says:

    Joe, apologies for the late reply.  I understand that the error message you're referring to (one-or-more-properties) is not very helpful; I'm personally working on resolving this for the upcoming 1.5 release.

    Tom and Howard – async support in the Graph client library has been a high priority for us, and we will be documenting its support along with a number of other improvements in the 1.5 release that will be available in the upcoming weeks.  Stay tuned!

    Thanks,

    Robert

  14. Ilya says:

    Hi Guys,

    Thanks for this lib. it defiantly saves dev time instead of calling REST services directly.

    Question about the differential queries:

    Will it supported in version 1.5?

    How would you recommend to handle Directory_BindingRedirection error? when I try to send requests to servers specified in the response body(instead of graph.windows.net), it says that specified api version is invalid.

  15. Karl Schulmeisters says:

    4 months with no new official content and rumour that there will be a new version released in the next few weeks

    Can we get some update on this?    What will the migration path be from 1.2.1

  16. Alessandro Alfano says:

    Hi, any update for 2.0.0. ? I saw a lot of changes in the API

  17. Jon Smith says:

    Hi, I tried to use 2.0.0 but it fails by hanging in graphConnection.List<User>(null, null). It seems that GraphConnection is now obsolete, but its not easy to see what replaces it.

    Sure would like some new documentation, and not just links to Office 365 SDKs which don't cover this.

  18. Matt Clark says:

    Hey Jon, I had similar issues with 2.0.0 of the library. After reverting to v1.0.3 we have had no issues.

  19. Alessandro Alfano says:

    Hi guys (Jon it drives me crazy too but I understand they are related, you will find clues with fiddler),

    I have looked deep in the console application graphApi example (the one with 2.0.0 version) and I found that the new object is ActiveDirectoryClient.

    ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,

                   async () => await AcquireTokenAsyncForApplication());

    Then you use it as an OData client (?)

    //*********************************************************************************************

               // Create a new User with a temp password

               //*********************************************************************************************

               IUser userToBeAdded = new User();

               userToBeAdded.DisplayName = "Sample App Demo User";

               userToBeAdded.UserPrincipalName = Helper.GetRandomString(10) + "@" + defaultDomain.Name;

               userToBeAdded.AccountEnabled = true;

               userToBeAdded.MailNickname = "SampleAppDemoUser";

               userToBeAdded.PasswordProfile = new PasswordProfile

               {

                   password = "TempP@ssw0rd!",

                   forceChangePasswordNextLogin = true

               };

               userToBeAdded.UsageLocation = "US";

               try

               {

                   activeDirectoryClient.Users.AddUserAsync(userToBeAdded).Wait();

                   Console.WriteLine("nNew User {0} was created", userToBeAdded.DisplayName);

               }

               catch (Exception e)

               {

                   Console.WriteLine("nError creating new user. {0} {1}", e.Message,

                       e.InnerException != null ? e.InnerException.Message : "");

               }

    Hey aadgraphtem, we want docs updated 😀

    with love,

    Al

  20. JonSmith says:

    Thanks for that Alessandro. It seems that The AzureAdSample of Graph API was updated to 2.0.1 at the end of November 2014. See github.com/…/WebApp-GraphAPI-DotNet

    Alessandro, you were right. Here is a piece of code to list users using the new interface:

                   ActiveDirectoryClient client = AuthenticationHelper.GetActiveDirectoryClient();

                   IPagedCollection<IUser> pagedCollection = await client.Users.ExecuteAsync();

                   if (pagedCollection != null)

                   {

                       do

                       {

                           List<IUser> usersList = pagedCollection.CurrentPage.ToList();

                           foreach (IUser user in usersList)

                           {

                               userList.Add((User) user);

                           }

                           pagedCollection = await pagedCollection.GetNextPageAsync();

                       } while (pagedCollection != null && pagedCollection.MorePagesAvailable);

                   }

    I really would like some documentation, but at least we have some working sample code. Thanks guys.

  21. JonSmith says:

    PS. To my last post. The AuthenticationHelper.GetActiveDirectoryClient() method is a bit tricky, and in my opinion is not that clear. The AuthenticationHelper.GetActiveDirectoryClient() method relies on two things:

    1. It needs on some application settings in the Web.config file. See Constants.cs and Web.Config
    2. It needs the AuthenticationHelper.token set, which happens in App_StartStartup.Auth.cs when UseOpenIdConnectAuthentication is started.

    Still puzzling out how to use this.

  22. Seketman says:

    I love this library!… but found the help in this page some weeks late 🙁

    To build dynamic queries I was using this little trick: <a href="whereisthecode.blogspot.com.ar/…/universal-predicatebuilder-tunned-for.html" target="_blank">Universal PredicateBuilder… tunned for Azure AD Graph API queries</a>

    Thanks guys!

  23. Alessandro Alfano says:

    Hi, another update (2.0.2) and still no feedback.

    I reverted my code to the old 1.0.7 because I "extended" Microsoft.WindowsAzure.ActiveDirectory with my custom ExtensionProperty using http calls. Please contact me if anyone is using that and would like to help with the new version 🙂

    Regards,

    Alessandro