Azure AD Graph客户端库批处理

时间:2016-03-23 22:04:06

标签: azure batch-processing azure-sdk-.net azure-ad-graph-api

有人可以告诉我是否可以使用批处理来添加组成员资格吗?

如果是的话,请给我一个例子

提前致谢

亲切的问候,

Snegha

1 个答案:

答案 0 :(得分:2)

根据documentation,Graph API支持批量处理。 Microsoft Azure Active Directory Client支持批处理。

您可以在此处找到大量示例以使用Azure AD Graph API:

特别是您可以在此处使用Graph API执行的大多数操作都有完整示例:

不幸的是,批处理不适用于导航属性,或者至少我找不到让它工作的方法......

让我们来看看documentation

  

OData批量请求的图谱API支持:

     
      
  • 查询是单个查询或函数调用。
  •   
  • 更改集是一组一个或多个插入,更新或删除操作,操作调用或服务调用。
  •   
  • 批处理是一个操作容器,包括一个或多个更改集和查询操作。
  •   
     

Graph API支持由。定义的功能的子集   OData规范:

     
      
  • 单个批次最多可包含五个查询和/或更改集合。
  •   
  • 更改集最多可包含一个源对象修改和最多20个add-link和delete-link操作   结合。更改集中的所有操作必须位于单个源上   实体。
  •   

以下是批处理请求语法:

https://graph.windows.net/TenantName/$batch?api-version=1.6

批处理请求通过一个 POST 指令发送到服务器。

有效内容是多部分MIME消息,包含批次及其组成查询和更改集。有效负载包括两种类型的MIME边界:

  • 批边界分隔批次中的每个查询和/或更改集。
  • 更改集边界可分隔更改集中的各个操作。

更改集中的单个请求与自行调用该操作时发出的请求相同。here is a sample request

您可以在此处找到完整的示例代码:azure-active-directory-batchprocessing 所以基本上,您需要获取身份验证令牌:

var authority = "https://login.microsoftonline.com/mytenantName.onmicrosoft.com";
var resource = "https://graph.windows.net/";
var clientId = "ClientId of the application in the Azure Active Directory";
var clientSecret = "ClientSecret of the application in the Azure Active Directory";

var token = new AuthenticationContext(authority, false).AcquireToken(resource,
        new ClientCredential(clientId, clientSecret)).AccessToken;

在您的问题中,您想将成员添加到群组(see Graph API Documentation on groups):

// Get the objectId of the group
var groupId = ...

// Get the member ids you'd like to add to the group
var memberIds = ...

以下是将成员添加到群组的代码:

private static async Task AddMemberToGroup(string token, string groupId, IList<string> memberIds)
{
    if (memberIds.Count > 100)
    {
        // A batch can contain up to 5 changesets. Each changeset can contain up to 20 operations.
        throw new InvalidOperationException("Cannot send more than 100 operation in an batch");
    }

    var batch = new BatchRequest("https://graph.windows.net/MyTenantName.onmicrosoft.com");

    // A changeset can contain up to 20 operations
    var takeCount = 20;
    var skipCount = 0;
    var take = memberIds.Skip(skipCount).Take(takeCount).ToList();
    while (take.Count > 0)
    {
        AddChangeset(batch, groupId, take);
        skipCount += takeCount;
        take = memberIds.Skip(skipCount).Take(takeCount).ToList();
    }

    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
        var response = await client.SendAsync(batch.Request);
    }
}

private static void AddChangeset(BatchRequest batch, string groupId, IEnumerable<string> memberIds)
{
    var changeset = batch.AddChangeSet();
    foreach (var memberId in memberIds)
    {
        // Create the HttpRequest to add a member to a group
        var request = AddMemberToGroupRequest(groupId, memberId);

        // Add the operation to the changeset
        changeset.AddOperation(request);
    }
}

private static HttpRequestMessage AddMemberToGroupRequest(string groupId, string memberId)
{
    // Create a request to add a member to a group
    var request = new HttpRequestMessage(HttpMethod.Post,
        $"https://graph.windows.net/MyTenantName.onmicrosoft.com/groups/{groupId}/$links/members?api-version=1.6");

    // Create the body of the request
    var jsonBody =
        JsonConvert.SerializeObject(new DirectoryObject($"https://graph.windows.net/MyTenantName.onmicrosoft.com/directoryObjects/{memberId}"));

    // Set the content
    request.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

    // Return the request
    return request;
}

public class BatchRequest
{
    private readonly MultipartContent _batchContent;

    public BatchRequest(string tenantUrl)
    {
        // Create the batch request
        Request = new HttpRequestMessage(HttpMethod.Post,
            $"{tenantUrl}/$batch?api-version=1.6");

        // Initializes the batch content
        _batchContent = new MultipartContent("mixed", "batch_" + Guid.NewGuid());
        Request.Content = _batchContent;
    }

    public HttpRequestMessage Request { get; }

    public ChangeSet AddChangeSet()
    {
        // Create a new changeset
        var changeSet = new ChangeSet();

        // Add the content of the changeset to the batch
        _batchContent.Add(changeSet.Content);

        // return the changeset
        return changeSet;
    }

    public HttpMessageContent CreateOperation(HttpRequestMessage request)
    {
        var content = new HttpMessageContent(request);
        content.Headers.ContentType = new MediaTypeHeaderValue("application/http");
        content.Headers.Add("Content-Transfer-Encoding", "binary");
        return content;
    }
}

public class ChangeSet
{
    public ChangeSet()
    {
        Content = new MultipartContent("mixed", "changeset_" + Guid.NewGuid());
    }

    public MultipartContent Content { get; }

    public void AddOperation(HttpRequestMessage request)
    {
        var operationContent = new HttpMessageContent(request);
        operationContent.Headers.ContentType = new MediaTypeHeaderValue("application/http");
        operationContent.Headers.Add("Content-Transfer-Encoding", "binary");
        Content.Add(operationContent);
    }
}

public class DirectoryObject
{
    public DirectoryObject(string url)
    {
        this.url = url;
    }
        public string url { get; }
}