/// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { CreateGroupResponse response = new CreateGroupResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Group", targetDepth)) { var unmarshaller = GroupUnmarshaller.Instance; response.Group = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("RequestId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.RequestId = unmarshaller.Unmarshall(context); continue; } } response.Status = (int)context.ResponseData.StatusCode; return(response); }
/// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { CreateGroupResponse response = new CreateGroupResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.IsStartElement) { if (context.TestExpression("CreateGroupResult", 2)) { UnmarshallResult(context, response); continue; } if (context.TestExpression("ResponseMetadata", 2)) { response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context); } } } return(response); }
public async Task <ActionResult> AddGroup([FromBody] CreateGroupResponse group) { if (!ModelState.IsValid) { return(BadRequest(new CommonResponse { Status = false })); } try { var newgroup = await _groupdata.CreateGroupAsync(group); if (newgroup == null) { return(BadRequest(new CommonResponse { Status = false })); } return(Ok(newgroup)); //CreatedAtRoute("GetGroupRoute", new { id = newgroup.groupid }, new CommonResponse { Status = true, id = newgroup.groupid}); } catch (Exception exp) { _Logger.LogError(exp.Message); return(BadRequest(new CommonResponse { Status = false })); } }
private static void UnmarshallResult(XmlUnmarshallerContext context, CreateGroupResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) { targetDepth += 2; } while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("Group", targetDepth)) { var unmarshaller = GroupUnmarshaller.Instance; response.Group = unmarshaller.Unmarshall(context); continue; } } } return; }
/// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { CreateGroupResponse response = new CreateGroupResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Group", targetDepth)) { var unmarshaller = GroupUnmarshaller.Instance; response.Group = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ResourceQuery", targetDepth)) { var unmarshaller = ResourceQueryUnmarshaller.Instance; response.ResourceQuery = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Tags", targetDepth)) { var unmarshaller = new DictionaryUnmarshaller <string, string, StringUnmarshaller, StringUnmarshaller>(StringUnmarshaller.Instance, StringUnmarshaller.Instance); response.Tags = unmarshaller.Unmarshall(context); continue; } } return(response); }
private static async Task SetGroupSettings(CreateGroupRequest request, CreateGroupResponse response, TraceWriter log) { GraphServiceClient client = ConnectADAL.GetGraphClient(); try { if (!request.AllowToAddGuests) { var groupUnifiedGuestSetting = new GroupSetting() { DisplayName = "Group.Unified.Guest", TemplateId = "08d542b9-071f-4e16-94b0-74abb372e3d9", Values = new List <SettingValue> { new SettingValue() { Name = "AllowToAddGuests", Value = "false" } } }; log.Info($"Setting setting in Group.Unified.Guest (08d542b9-071f-4e16-94b0-74abb372e3d9), AllowToAddGuests = false"); await client.Groups[response.GroupId].Settings.Request().AddAsync(groupUnifiedGuestSetting); } } catch (Exception e) { log.Error($"Error setting AllowToAddGuests for group {response.GroupId}: {e.Message }\n\n{e.StackTrace}"); } }
private void OnCreateGroup(CreateGroupResponse response) { Debug.Log("Group Created: " + response.GroupName + " - " + response.Group.Id); var prevRequest = (CreateGroupRequest)response.Request; EntityGroupPairs.Add(new KeyValuePair <string, string>(prevRequest.Entity.Id, response.Group.Id)); GroupNameById[response.Group.Id] = response.GroupName; }
public async Task <CreateGroupResponse> CreateGroup(CreateGroupRequest createGroupRequest) { NameValueCollection header = new NameValueCollection(); header.Add(Constants.ACCESS_TOKEN_STRING, this.Session.GetAccessToken()); string request = JsonConvert.SerializeObject(createGroupRequest); CreateGroupResponse response = await APICallHandler.PostAsync <CreateGroupResponse>(header, string.Format(Constants.CREATE_GROUP_URL, Constants.API_ROOT), request); return(await Task.FromResult(response)); }
/// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { CreateGroupResponse response = new CreateGroupResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Arn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Arn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("CreationTimestamp", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.CreationTimestamp = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Id", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Id = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("LastUpdatedTimestamp", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.LastUpdatedTimestamp = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("LatestVersion", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.LatestVersion = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("LatestVersionArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.LatestVersionArn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Name", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Name = unmarshaller.Unmarshall(context); continue; } } return(response); }
public async override Task <CreateGroupResponse> CreateGroup(CreateGroupRequest request, ServerCallContext context) { try { var result = new CreateGroupResponse { Success = true }; var valid = GroupValidate(request.Group); if (!valid.success) { result.Success = false; result.Message = valid.message; return(result); } var userIdentifier = GetUserIdentifier(context); var user = await _groupStore.GetUser(userIdentifier); if (user == null) { user = new User { Identifier = userIdentifier }; } var group = new Group { Password = request.Group.Password, UsersGroups = new List <UserGroup> { new UserGroup { GroupLabel = request.Group.Label, UserName = request.Group.UserName, UserRole = UserRole.Owner, UserIcon = request.Group.UserIcon, User = user } } }; await _groupStore.CreateGroup(group); result.Id = group.Id; return(result); } catch (Exception ex) { _logger.LogError(ex, ex.Message); return(new CreateGroupResponse { Success = false, Message = ex.Message }); } }
public IActionResult AddGroup([FromBody] CreateGroupRequest newGroup) { var userId = Request.GetUserId(); Ensure.Any.IsNotNull(newGroup, nameof(newGroup), opt => opt.WithException(new ArgumentNullException(nameof(newGroup)))); var newId = _groupFacade.CreateGroup(userId, newGroup.Title, newGroup.Tags, newGroup.Description, newGroup.Size, newGroup.MoneyPerUser, newGroup.IsPrivate, newGroup.GroupType); var response = new CreateGroupResponse(newId); return(Ok(response)); }
public static CreateGroupResponse Unmarshall(UnmarshallerContext context) { CreateGroupResponse createGroupResponse = new CreateGroupResponse(); createGroupResponse.HttpResponse = context.HttpResponse; createGroupResponse.RequestId = context.StringValue("CreateGroup.RequestId"); createGroupResponse.Code = context.IntegerValue("CreateGroup.Code"); createGroupResponse.Message = context.StringValue("CreateGroup.Message"); createGroupResponse.Success = context.BooleanValue("CreateGroup.Success"); return(createGroupResponse); }
private static async Task AddUsersToAdminGroup(IAmazonIdentityManagementService client, CancellationToken token) { CreateGroupRequest groupRequest = new CreateGroupRequest("Admins"); CreateGroupResponse response = await client.CreateGroupAsync(groupRequest, token); AddUserToGroupRequest request = new AddUserToGroupRequest("Admins", SomeUser); var foo = await client.AddUserToGroupAsync(request, token); request = new AddUserToGroupRequest("Admins", AnotherUser); foo = await client.AddUserToGroupAsync(request, token); }
public static CreateGroupResponse Unmarshall(UnmarshallerContext context) { CreateGroupResponse createGroupResponse = new CreateGroupResponse(); createGroupResponse.HttpResponse = context.HttpResponse; createGroupResponse.RequestId = context.StringValue("CreateGroup.RequestId"); createGroupResponse.Id = context.StringValue("CreateGroup.Id"); createGroupResponse.GbId = context.StringValue("CreateGroup.GbId"); createGroupResponse.GbIp = context.StringValue("CreateGroup.GbIp"); createGroupResponse.GbPort = context.LongValue("CreateGroup.GbPort"); return(createGroupResponse); }
public static CreateGroupResponse Unmarshall(UnmarshallerContext context) { CreateGroupResponse createGroupResponse = new CreateGroupResponse(); createGroupResponse.HttpResponse = context.HttpResponse; createGroupResponse.RequestId = context.StringValue("CreateGroup.RequestId"); CreateGroupResponse.CreateGroup_Group group = new CreateGroupResponse.CreateGroup_Group(); group.GroupName = context.StringValue("CreateGroup.Group.GroupName"); group.Comments = context.StringValue("CreateGroup.Group.Comments"); group.CreateDate = context.StringValue("CreateGroup.Group.CreateDate"); createGroupResponse.Group = group; return(createGroupResponse); }
public async Task <(Guid, bool)> CreatAsync(string name) { HttpResponseMessage response = await client.PostAsJsonAsync( controllerPath, new CreateGroupRequest { Name = name }); if (response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.Conflict) { CreateGroupResponse group = await response.Content.ReadAsAsync <CreateGroupResponse>(); bool IsNewGroup = response.IsSuccessStatusCode; return(group.Id, IsNewGroup); } else { throw new UnauthorizedAccessException($"Unouthorized group creation '{name}'"); } }
public GroupInfo CreateGroup( string name, string code, RichTextInfo desc, Identifier grpTypeId, Identifier ownerId) { CreateGroupRequest request = new CreateGroupRequest() { Name = name, Code = code, Description = desc, GroupTypeId = grpTypeId, OwnerOrgUnitId = ownerId }; CreateGroupResponse response = CallWebService < IOrgUnitManagementServicev1_0, CreateGroupRequest, CreateGroupResponse>( m_service1_0, request, (s, q) => s.CreateGroup(q)); return(response.Group); }
public CreateGroupResponse Create(CreateGroupRequest request) { var response = new CreateGroupResponse(); try { var group = request.MapTo<Group>(); DataContext.Groups.Add(group); DataContext.SaveChanges(); response.IsSuccess = true; response.Message = "Group item has been added successfully"; } catch (DbUpdateException dbUpdateException) { response.IsSuccess = false; response.Message = dbUpdateException.Message; } return response; }
static bool CreateGroup(string url, Credentials c, string name, string description) { Console.WriteLine("Creating group..."); ArticulateOnline ao = new ArticulateOnline { Url = url }; CreateGroupRequest request = new CreateGroupRequest { Credentials = c, Name = name, Description = description }; CreateGroupResponse response = ao.CreateGroup(request); return(response.Success); }
private static async Task SetGroupMembership(CreateGroupResponse response, List <User> owners, List <User> members, TraceWriter log) { GraphServiceClient client = ConnectADAL.GetGraphClient(); foreach (var owner in owners) { try { log.Info($"Setting {owner.Mail} as Owner for the group."); await client.Groups[response.GroupId].Owners.References.Request().AddAsync(owner); } catch (ServiceException ex) { if (ex.Error.Code == "Request_BadRequest" && ex.Error.Message.Contains("added object references already exist")) { // Skip any already existing member } else { throw ex; } } } foreach (var member in members) { try { log.Info($"Setting {member.Mail} as Member for the group."); await client.Groups[response.GroupId].Owners.References.Request().AddAsync(member); } catch (ServiceException ex) { if (ex.Error.Code == "Request_BadRequest" && ex.Error.Message.Contains("added object references already exist")) { // Skip any already existing member } else { throw ex; } } } }
public CreateGroupResponse Create(CreateGroupRequest request) { var response = new CreateGroupResponse(); try { var group = request.MapTo <Group>(); DataContext.Groups.Add(group); DataContext.SaveChanges(); response.IsSuccess = true; response.Message = "Group item has been added successfully"; } catch (DbUpdateException dbUpdateException) { response.IsSuccess = false; response.Message = dbUpdateException.Message; } return(response); }
public Task <GroupDTO> CreateNewGroupAsync(CreateGroupDataModel createGroupDataModel, CancellationTokenSource cancellationTokenSource) => Task.Run(async() => { if (!CrossConnectivity.Current.IsConnected) { throw new InvalidOperationException(AppConsts.ERROR_INTERNET_CONNECTION); } GroupDTO createdGroup = null; CreateGroupRequest createGroupRequest = new CreateGroupRequest() { AccessToken = GlobalSettings.Instance.UserProfile.AccesToken, Data = createGroupDataModel, Url = GlobalSettings.Instance.Endpoints.GroupsEndpoints.CreateGroup }; try { CreateGroupResponse createGroupResponse = await _requestProvider.PostAsync <CreateGroupRequest, CreateGroupResponse>(createGroupRequest); if (createGroupResponse != null) { createdGroup = BuildGroup(createGroupResponse); } else { throw new InvalidOperationException(GroupsService._CREATE_GROUP_COMMON_ERROR_MESSAGE); } } catch (ServiceAuthenticationException exc) { _identityUtilService.RefreshToken(); throw exc; } catch (Exception exc) { Crashes.TrackError(exc); throw; } return(createdGroup); }, cancellationTokenSource.Token);
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { CreateGroupResponse response = new CreateGroupResponse(); while (context.Read()) { if (context.IsStartElement) { if (context.TestExpression("CreateGroupResult", 2)) { response.CreateGroupResult = CreateGroupResultUnmarshaller.GetInstance().Unmarshall(context); continue; } if (context.TestExpression("ResponseMetadata", 2)) { response.ResponseMetadata = ResponseMetadataUnmarshaller.GetInstance().Unmarshall(context); } } } return(response); }
public async Task <GroupResponse> CreateGroupAsync(CreateGroupResponse group1) { GroupResponse response = new GroupResponse(); Group group = new Group(); group.group_name = group1.group_name; group.group_created_by = group1.group_created_by; group.is_simplified_depts = group1.is_simplified_depts; _Context.groups.Add(group); try { await _Context.SaveChangesAsync(); } catch (Exception exp) { _Logger.LogError($"Error in {nameof(CreateGroupAsync)}: " + exp.Message); } foreach (var x in group1.groupMembers) { GroupMember groupMember = new GroupMember(); groupMember.groupId = group.groupid; groupMember.userId = x.userId; _Context.groupMembers.Add(groupMember); try { await _Context.SaveChangesAsync(); } catch (Exception exp) { _Logger.LogError($"Error in {nameof(CreateGroupAsync)}: " + exp.Message); } } response = ModelData(group); return(response); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req, TraceWriter log) { //Set up the results to return to caller CreateGroupResponse result = new CreateGroupResponse() { CreatedChannels = new List <CreateChannelResponse>() }; try { var content = await req.Content.ReadAsStringAsync(); log.Info($"Function was triggered with the following payload { content }"); try { var request = JsonConvert.DeserializeObject <CreateGroupRequest>(content); log.Info("Successfully deserialized Json data"); //Get Azure OAuth access token string accessToken = await(new GraphApiUtility(log)).GetGraphApiAuthenticationToken(); List <string> owners = new List <string>(); owners.Add(request.OwnerUpn); // Graph API create team only supports delegated access permission. Must add service principal to owner of the Group string teamServicePrincipal = KeyVaultUtility.GetSecret(ConfigurationManager.AppSettings["kv:ServicePrincipalNameSecretName"], log).Result; if (teamServicePrincipal.ToLower() != request.OwnerUpn.ToLower()) { owners.Add(teamServicePrincipal); } //Use Pnp to create a new Group var newGroup = UnifiedGroupsUtility.CreateUnifiedGroup(displayName: request.Displayname, description: request.Description, mailNickname: request.EmailAlias, accessToken: accessToken, owners: owners.ToArray(), members: owners.ToArray(), isPrivate: request.IsPrivate, retryCount: 10, delay: 500); //Set up the results to return to caller result.GroupCreated = true; result.GroupId = new Guid(newGroup.GroupId); result.GroupSiteUrl = newGroup.SiteUrl; if (request.CreateTeam) { //Add apps such as Team (& Channel), Planner, and OneNote to Group await AddAppsToTeam(request, result.GroupId, result, log); } return(new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent(JsonConvert.SerializeObject(result), System.Text.Encoding.UTF8, "application/json") }); } catch (JsonReaderException jsonError) { log.Error($"Json parsing error in incoming request: {jsonError.Message}"); result.GroupCreated = false; result.Message = $"Invalid Json request: { jsonError.Message }"; return(new HttpResponseMessage() { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(JsonConvert.SerializeObject(result), System.Text.Encoding.UTF8, "application/json") }); } } catch (Exception ex) { log.Error(ex.ToDetailedString()); result.GroupCreated = false; result.Message = $"Error: { ex.ToDetailedString() }"; return(new HttpResponseMessage() { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(JsonConvert.SerializeObject(result), System.Text.Encoding.UTF8, "application/json") }); } }
public async Task <GroupResponse> CreateGroupAsync(CreateGroupResponse group1) { GroupResponse response = new GroupResponse(); Group group = new Group(); group.group_name = group1.group_name; group.group_created_by = group1.group_created_by; group.is_simplified_depts = group1.is_simplified_depts; _Context.groups.Add(group); try { await _Context.SaveChangesAsync(); } catch (Exception exp) { _Logger.LogError($"Error in {nameof(CreateGroupAsync)}: " + exp.Message); } foreach (var x in group1.groupMembers) { GroupMember groupMember = new GroupMember(); groupMember.groupId = group.groupid; groupMember.userId = x.userId; _Context.groupMembers.Add(groupMember); try { await _Context.SaveChangesAsync(); } catch (Exception exp) { _Logger.LogError($"Error in {nameof(CreateGroupAsync)}: " + exp.Message); } } response = ModelData(group); for (int i = 0; i < group1.groupMembers.Count; i++) { for (int j = i + 1; j < group1.groupMembers.Count; j++) { Friend friend = new Friend(); var frdexist = _Context.friends.SingleOrDefault( c => (c.userId == group1.groupMembers[i].userId && c.friendId == group1.groupMembers[j].userId) || (c.userId == group1.groupMembers[j].userId && c.friendId == group1.groupMembers[i].userId)); if (frdexist == null) { friend.friendId = group1.groupMembers[j].userId; friend.userId = group1.groupMembers[i].userId; _Context.friends.Add(friend); try { await _Context.SaveChangesAsync(); } catch (Exception exp) { _Logger.LogError($"Error in {nameof(CreateGroupAsync)}: " + exp.Message); } } } } return(response); }
/// <summary> /// Add apps such as Team (& Channel), Planner, and OneNote to Group /// </summary> private async static Task AddAppsToTeam(CreateGroupRequest request, Guid groupId, CreateGroupResponse result, TraceWriter log) { //If options to create additional app if (request.CreateTeam || request.CreateNotebook || request.CreatePlanner) { int pauseTime = int.Parse(ConfigurationManager.AppSettings["gph:PauseTimeAfterGroupCreationInMilliseonds"]); log.Info($"Pausing for { pauseTime } milliseconds after Group Creation"); System.Threading.Thread.Sleep(pauseTime); using (HttpClient delegatedAccessClient = new HttpClient()) { //Get deletgate access token string delegatedToken = await new GraphApiUtility(log).GetGraphApiDelegatedAuthenticationToken(); delegatedAccessClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", delegatedToken); if (request.CreateTeam) { //Set the team settings to default if none was passed in if (request.TeamSettings == null) { request.TeamSettings = new TeamSettings(); } //Create a team result.TeamCreated = await AddTeamToUnifiedGroup(delegatedAccessClient, result.GroupId, request.TeamSettings, log); //Create channel if the request has channel request and Team was created if (result.TeamCreated && request.TeamChannels != null && request.TeamChannels.Count > 0) { for (int i = 0; i < request.TeamChannels.Count; i++) { if (!string.IsNullOrEmpty(request.TeamChannels[i].DisplayName)) { var channel = await AddChannelsToUnifiedGroup(delegatedAccessClient, result.GroupId, request.TeamChannels[i], log); if (channel != null) { result.NumberOfChannelCreated++; } } } //Add default chat thread var channels = await GetChannelsFromGroup(delegatedAccessClient, result.GroupId, log); if (channels != null && channels.Count > 0) { for (int i = 0; i < channels.Count; i++) { await AddDefaultChatThreadToTeamChannel(delegatedAccessClient, result.GroupId, channels[i], log); } } } } if (request.CreatePlanner) { result.PlannerCreated = await AddPlannerToUnifiedGroup(delegatedAccessClient, result.GroupId, request.PlannerTitle, log); } if (request.CreateNotebook) { result.NotebookCreated = await AddNotebookToUnifiedGroup(delegatedAccessClient, result.GroupId, request.NotebookTitle, log); } } } }
private static async Task UserAndGroupOps(IdentityClient client, string compartmentId) { // create a test user CreateUserDetails createUserDetails = new CreateUserDetails { CompartmentId = compartmentId, Name = userName, Description = "testing oci sdk for .NET" }; CreateUserRequest createUserRequest = new CreateUserRequest { CreateUserDetails = createUserDetails }; CreateUserResponse createUserResponse = await client.CreateUser(createUserRequest); User user = createUserResponse.User; logger.Info($"user created, Name : {user.Name} , ID : {user.Id}"); // create a test group CreateGroupDetails createGroupDetails = new CreateGroupDetails { CompartmentId = compartmentId, Name = "oci-dotnetsdk-testgroup", Description = "testing oci sdk for .NET" }; CreateGroupRequest createGroupRequest = new CreateGroupRequest { CreateGroupDetails = createGroupDetails }; CreateGroupResponse createGroupResponse = await client.CreateGroup(createGroupRequest); logger.Info($"new group created, Name : {createGroupResponse.Group.Name} , Id : {createGroupResponse.Group.Id}"); Group group = createGroupResponse.Group; // add the user to the group logger.Info("Adding new user to the new group"); AddUserToGroupDetails addUserToGroupDetails = new AddUserToGroupDetails { UserId = user.Id, GroupId = group.Id }; AddUserToGroupRequest addUserToGroupRequest = new AddUserToGroupRequest { AddUserToGroupDetails = addUserToGroupDetails }; AddUserToGroupResponse addUserToGroupResponse = await client.AddUserToGroup(addUserToGroupRequest); logger.Info($"Added user: {user.Name} to the group: {group.Name}"); // remove user from the group logger.Info($"removing user: {user.Name} from the group: {group.Name}"); RemoveUserFromGroupRequest removeUserFromGroupRequest = new RemoveUserFromGroupRequest { UserGroupMembershipId = addUserToGroupResponse.UserGroupMembership.Id }; await client.RemoveUserFromGroup(removeUserFromGroupRequest); // delete the user logger.Info($"deleting the user: {user.Name}"); DeleteUserRequest deleteUserRequest = new DeleteUserRequest { UserId = user.Id }; await client.DeleteUser(deleteUserRequest); // delete the group logger.Info($"deleting the group: {group.Name}"); DeleteGroupRequest deleteGroupRequest = new DeleteGroupRequest { GroupId = group.Id }; await client.DeleteGroup(deleteGroupRequest); logger.Info("Finished delete user and group"); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] CreateGroupRequest request, TraceWriter log) { try { if (string.IsNullOrWhiteSpace(request.Name)) { throw new ArgumentException("Parameter cannot be null", "Name"); } if (string.IsNullOrWhiteSpace(request.Description)) { throw new ArgumentException("Parameter cannot be null", "Description"); } var members = await GetUsers(request.Members); var owners = await GetUsers(request.Owners); var content = await GenerateStringContent(request, owners, members); Uri uri = new Uri($"https://graph.microsoft.com/v1.0/groups"); string bearerToken = await ConnectADAL.GetBearerToken(); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken); var response = await client.PostAsync(uri, content); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); dynamic responseJson = JObject.Parse(responseBody); var createGroupResponse = new CreateGroupResponse { DisplayName = responseJson.displayName, Mail = responseJson.mail, GroupId = responseJson.id }; await SetGroupSettings(request, createGroupResponse, log); await SetGroupMembership(createGroupResponse, owners, members, log); return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new ObjectContent <CreateGroupResponse>(createGroupResponse, new JsonMediaTypeFormatter()) })); } string responseMsg = await response.Content.ReadAsStringAsync(); dynamic errorJson = JsonConvert.DeserializeObject(responseMsg); return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new ObjectContent <string>($"{errorJson.error.code}: {errorJson.error.message}", new JsonMediaTypeFormatter()) })); } catch (Exception e) { log.Error($"Error: {e.Message }\n\n{e.StackTrace}"); return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter()) })); } }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] CreateGroupRequest request, TraceWriter log) { try { if (string.IsNullOrWhiteSpace(request.Name)) { throw new ArgumentException("Parameter cannot be null", "Name"); } if (string.IsNullOrWhiteSpace(request.Description)) { throw new ArgumentException("Parameter cannot be null", "Description"); } string mailNickName = await GetUniqueMailAlias(request); string displayName = GetDisplayName(request); GraphServiceClient client = ConnectADAL.GetGraphClient(GraphEndpoint.Beta); var newGroup = new Group { DisplayName = displayName, Description = GetDescription(request.Description, 1000), MailNickname = mailNickName, MailEnabled = true, SecurityEnabled = false, Visibility = request.Public ? "Public" : "Private", GroupTypes = new List <string> { "Unified" }, Classification = request.Classification }; var addedGroup = await client.Groups.Request().AddAsync(newGroup); var createGroupResponse = new CreateGroupResponse { GroupId = addedGroup.Id, DisplayName = displayName, Mail = addedGroup.Mail }; try { if (!request.AllowToAddGuests) { var groupUnifiedGuestSetting = new GroupSetting() { DisplayName = "Group.Unified.Guest", TemplateId = "08d542b9-071f-4e16-94b0-74abb372e3d9", Values = new List <SettingValue> { new SettingValue() { Name = "AllowToAddGuests", Value = "false" } } }; log.Info($"Setting setting in Group.Unified.Guest (08d542b9-071f-4e16-94b0-74abb372e3d9), AllowToAddGuests = false"); await client.Groups[addedGroup.Id].Settings.Request().AddAsync(groupUnifiedGuestSetting); } } catch (Exception e) { log.Error($"Error setting AllowToAddGuests for group {addedGroup.Id}: {e.Message }\n\n{e.StackTrace}"); } return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new ObjectContent <CreateGroupResponse>(createGroupResponse, new JsonMediaTypeFormatter()) })); } catch (Exception e) { log.Error($"Error: {e.Message }\n\n{e.StackTrace}"); return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) { Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter()) })); } }