Example #1
0
 public void Add(Group group)
 {
     lock (this.ThisLock)
     {
         _table[group] = new GroupManager(group);
     }
 }
            public void CreatesAddToGroupCommandOnAdd()
            {
                // Arrange
                var connection = new Mock<IConnection>();
                var message = default(ConnectionMessage);

                connection.Setup(m => m.Send(It.IsAny<ConnectionMessage>()))
                          .Callback<ConnectionMessage>(m =>
                          {
                              message = m;

                              Assert.Equal("c-1", m.Signal);
                              Assert.NotNull(m.Value);
                              var command = m.Value as Command;
                              Assert.NotNull(command);
                              Assert.NotNull(command.Id);
                              Assert.Equal(CommandType.AddToGroup, command.CommandType);
                              Assert.Equal("Prefix.MyGroup", command.Value);
                              Assert.True(command.WaitForAck);
                          });

                var groupManager = new GroupManager(connection.Object, "Prefix");

                // Act
                groupManager.Add("1", "MyGroup");
            }
Example #3
0
        public HubContext(Func<string, ClientHubInvocation, IEnumerable<string>, Task> send, string hubName, IConnection connection)
        {
            _send = send;
            _hubName = hubName;
            _connection = connection;

            Clients = new ClientProxy(send, hubName);
            Groups = new GroupManager(connection, _hubName);
        }
            public void ThrowsIfConnectionIdIsNull()
            {
                // Arrange
                var connection = new Mock<IConnection>();
                connection.Setup(m => m.Send(It.IsAny<ConnectionMessage>()));
                var groupManager = new GroupManager(connection.Object, "Prefix");

                // Assert
                Assert.ThrowsAsync<ArgumentNullException>(() => groupManager.Remove(null, "SomeGroup"));
            }
Example #5
0
            public void ThrowsIfGroupIsNull()
            {
                // Arrange
                var connection = new Mock<IConnection>();
                connection.Setup(m => m.Send(It.IsAny<ConnectionMessage>()));
                var groupManager = new GroupManager(connection.Object, "Prefix");

                // Assert
                Assert.Throws<ArgumentNullException>(() => groupManager.Add("1", null));
            }
Example #6
0
        public void Add(Group group, IEnumerable<Key> keys)
        {
            lock (_thisLock)
            {
                var groupManager = new GroupManager(group);

                _table[group] = groupManager;

                if (keys == null) return;

                foreach (var key in keys)
                {
                    groupManager.Set(key, true);
                }
            }
        }
Example #7
0
        void INotificationService.CloseRoom(IEnumerable <ChatUser> users, ChatRoom room)
        {
            // Kick all people from the room.
            foreach (var user in users)
            {
                foreach (var client in user.ConnectedClients)
                {
                    // Kick the user from this room
                    Clients[client.Id].kick(room.Name);

                    // Remove the user from this the room group so he doesn't get the leave message
                    GroupManager.RemoveFromGroup(client.Id, room.Name).Wait();
                }
            }

            // Tell the caller the room was successfully closed.
            Caller.roomClosed(room.Name);
        }
Example #8
0
        private void Remove(PointBlankPlayer executor, string[] args)
        {
            if (args.Length < 2)
            {
                UnturnedChat.SendMessage(executor, Translations["Base_NotEnoughArgs"], ConsoleColor.Red);
                return;
            }
            Group group = Group.Find(args[1]);

            if (group == null)
            {
                UnturnedChat.SendMessage(executor, Translations["Group_NotFound"], ConsoleColor.Red);
                return;
            }

            GroupManager.RemoveGroup(group);
            UnturnedChat.SendMessage(executor, Translations["Group_Removed"], ConsoleColor.Green);
        }
 public SecurityClaimConfigurationDataController(
     RoleManager roleManager,
     SecurityClaimManager claimsManager,
     SecurityPoolManager poolManager,
     ClientAdminContextAccessor clientContextAccessor,
     IAuthorizationService authorizationService,
     ILogger <ClientRolesDataController> logger,
     UserManager userManager,
     GroupManager groupManager
     )
     : base(logger)
 {
     _roleManager   = roleManager;
     _poolManager   = poolManager;
     _claimsManager = claimsManager;
     _userManager   = userManager;
     _groupManager  = groupManager;
 }
Example #10
0
        public void ChangeActiveGroupItem(int groupID)
        {
            if (ActiveGroupID != groupID)
            {
                ActiveGroupID = groupID;

                var group = GroupManager.GetGroup(ActiveGroupID);
                SelectedGroupNameTextBox.Text           = group.Name;
                SelectedGroupHorizontalAxisTextBox.Text = group.HorizontalAxis;

                foreach (GroupSettingsItem item in GroupsStackPanel.Children)
                {
                    item.ChangeColorMode(item.ID == groupID);
                }

                InitAttributes();
            }
        }
Example #11
0
        public async Task <ActionResult> EditGroup(string groupId)
        {
            if (string.IsNullOrWhiteSpace(groupId))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            var group = await GroupManager.FindByIdAsync(groupId);

            var editGroup = new GroupViewModel()
            {
                GroupId          = group.GroupId,
                GroupName        = group.GroupName,
                GroupDescription = group.GroupDescription
            };

            return(View(editGroup));
        }
        //public abstract IList<SecurityClaimConfig> configurations { get; set; }

        public SecurityUserRoleClaims(
            IContextAccessor <AdminContext> adminContextAccessor,
            DirectoryManager directoryManager,
            SecurityPoolManager poolManager,
            RoleManager roleManager,
            UserManager userManager,
            IEnumerable <ISecurityGroupProvider> groupsProvider,
            GroupManager groupManager
            )
        {
            _adminContextAccessor = adminContextAccessor;
            _directoryManager     = directoryManager;
            _poolManager          = poolManager;
            _roleManager          = roleManager;
            _userManager          = userManager;
            _groupsProvider       = groupsProvider;
            _groupManager         = groupManager;
        }
Example #13
0
        public void CreateGroup()
        {
            if (!RequireNotInGroup())
            {
                return;
            }

            var group = GroupManager.TryCreateGroup(User);

            if (group == null)
            {
                User.Send(GameMessage.GroupCreateFailedUnknownReason, ServerMessageType.GUI);
            }
            else
            {
                User.Send(GameMessage.GroupCreated, ServerMessageType.GUI);
            }
        }
Example #14
0
        public virtual void DeleteGroupMembers(HttpContext context)
        {
            YZRequest request            = new YZRequest(context);
            int       groupid            = request.GetInt32("groupid");
            JArray    jPost              = request.GetPostData <JArray>();
            BPMObjectNameCollection uids = jPost.ToObject <BPMObjectNameCollection>();

            using (IYZDbProvider provider = YZDbProviderManager.DefaultProvider)
            {
                using (IDbConnection cn = provider.OpenConnection())
                {
                    foreach (string uid in uids)
                    {
                        GroupManager.DeleteGroupMember(provider, cn, groupid, uid);
                    }
                }
            }
        }
Example #15
0
        protected override void OnStrategyStart()
        {
            //
            barChartGroup = new Group("Bars");

            barChartGroup.Add("Pad", DataObjectType.Int, 0);
            barChartGroup.Add("SelectorKey", DataObjectType.String, "VWAP " + Instrument.Symbol);

            //
            fillChartGroup = new Group("Fills");

            fillChartGroup.Add("Pad", DataObjectType.Int, 0);
            fillChartGroup.Add("SelectorKey", DataObjectType.String, "VWAP " + Instrument.Symbol);

            //
            GroupManager.Add(barChartGroup);
            GroupManager.Add(fillChartGroup);
        }
Example #16
0
        private void ChangeSelectedGroupHorizontalAxisCardButton_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            ChangeSelectedGroupHorizontalAxisCardButton.Background = ConvertColor.ConvertStringColorToSolidColorBrush(ColorManager.Secondary100);

            Mouse.OverrideCursor = Cursors.Wait;

            string newHorizontalAxis = SelectedGroupHorizontalAxisTextBox.Text;

            if (!newHorizontalAxis.Equals(string.Empty))
            {
                GroupManager.GetGroup(ActiveGroupID).HorizontalAxis = newHorizontalAxis;
                GroupManager.SaveGroups();

                //TODO update charts
            }

            Mouse.OverrideCursor = null;
        }
Example #17
0
        protected override void OnStrategyStart()
        {
            //
            barChartGroup = new Group("Bars");

            barChartGroup.Add("Pad", 0);
            barChartGroup.Add("SelectorKey", Instrument.Symbol);

            //
            fillChartGroup = new Group("Fills");

            fillChartGroup.Add("Pad", 0);
            fillChartGroup.Add("SelectorKey", Instrument.Symbol);

            //
            GroupManager.Add(barChartGroup);
            GroupManager.Add(fillChartGroup);
        }
Example #18
0
        /// <summary>
        ///     Checks whether this <see cref="IAuthorizable"/> is granted the given permission.
        /// </summary>
        /// <param name="authorizable">The <see cref="IAuthorizable"/> to authorize.</param>
        /// <param name="permission">The permission to check.</param>
        /// <returns>Returns <c>true</c> when the sets grant the given permission.</returns>
        public static bool IsAuthorized(this IAuthorizable authorizable, string permission)
        {
            var permissionsSets = new List <Dictionary <string, Permission> >();

            switch (authorizable)
            {
            case Guest guest:
                permissionsSets.Add(GroupManager.GetGuestGroup().Permissions);
                permissionsSets.AddRange(Pool.Server.Groups.FindAll(@group => @group.SortValue <= GroupManager.GetGuestGroup().SortValue).OrderBy(_ => _.SortValue).Select(_ => _.Permissions));

                //if (guest.ActiveChannel != null && guest.ActiveChannel.MemberPermissions.ContainsKey(guest.InternalId)) {
                //    permissionsSets.Add(guest.ActiveChannel.MemberPermissions[guest.InternalId]);
                //}

                permissionsSets.Add(guest.Permissions);

                break;

            case Member member:
                permissionsSets.AddRange(member.Groups.OrderBy(_ => _.SortValue).Select(_ => _.Permissions));
                if (member.Groups.Count > 0)
                {
                    permissionsSets.AddRange(Pool.Server.Groups.FindAll(@group => @group.SortValue <= member.Groups.Select(_ => _.SortValue).Min()).OrderBy(_ => _.SortValue).Select(_ => _.Permissions));
                }

                //if (member.ActiveChannel != null && member.ActiveChannel.MemberPermissions.ContainsKey(member.InternalId)) {
                //    permissionsSets.Add(member.ActiveChannel.MemberPermissions[member.InternalId]);
                //}

                permissionsSets.Add(member.Permissions);

                break;

            case Group group:
                permissionsSets.Add(group.Permissions);

                break;

            default:
                return(false);
            }

            return(IsAuthorized(permission, permissionsSets.ToArray()));
        }
Example #19
0
        private void Grid_Drop(object sender, System.Windows.DragEventArgs e)
        {
            Mouse.OverrideCursor = Cursors.Wait;

            string channelName = e.Data.GetData(typeof(string)).ToString();

            var group = GroupManager.GetGroup(ChartName);

            if (group != null)
            {
                if (group.GetAttribute(channelName) == null)
                {
                    GroupManager.GetGroup(ChartName).AddAttribute(channelName, ColorManager.GetChartColor, 1);
                }
            }
            else
            {
                if (!channelNames.Contains(channelName))
                {
                    channelNames.Add(channelName);

                    string oldName = ChartName;

                    var temporaryGroup = GroupManager.GetGroup($"Temporary{GroupManager.TemporaryGroupIndex}");

                    while (temporaryGroup != null)
                    {
                        GroupManager.TemporaryGroupIndex++;
                        temporaryGroup = GroupManager.GetGroup($"Temporary{GroupManager.TemporaryGroupIndex}");
                    }

                    ChartName = $"Temporary{GroupManager.TemporaryGroupIndex}";

                    GroupManager.AddGroup(GroupManager.MakeGroupWirhAttributes(ChartName, channelNames));
                    ((DriverlessMenu)MenuManager.GetTab(TextManager.DriverlessMenuName).Content).ReplaceChannelWithTemporaryGroup(oldName, ChartName);
                }
            }

            GroupManager.SaveGroups();
            ((GroupSettings)((SettingsMenu)MenuManager.GetTab(TextManager.SettingsMenuName).Content).GetTab(TextManager.GroupsSettingsName).Content).InitGroups();
            ((DriverlessMenu)MenuManager.GetTab(TextManager.DriverlessMenuName).Content).BuildCharts();

            Mouse.OverrideCursor = null;
        }
Example #20
0
        public void parse(GameClient Session, ClientMessage Event)
        {
            int num = Event.PopWiredInt32();

            if (num > 0 && (Session != null && Session.GetHabbo() != null))
            {
                Session.GetHabbo().GroupID = 0;
                if (Session.GetHabbo().InRoom)
                {
                    Room          class14_ = Session.GetHabbo().CurrentRoom;
                    RoomUser      @class   = class14_.GetRoomUserByHabbo(Session.GetHabbo().Id);
                    ServerMessage Message  = new ServerMessage(28u);
                    Message.AppendInt32(1);
                    @class.Serialize(Message);
                    class14_.SendMessage(Message, null);
                }
                using (DatabaseClient class2 = PhoenixEnvironment.GetDatabase().GetClient())
                {
                    class2.ExecuteQuery("UPDATE user_stats SET groupid = 0 WHERE Id = " + Session.GetHabbo().Id + " LIMIT 1;");
                }
                DataTable dataTable_ = Session.GetHabbo().GroupMemberships;
                if (dataTable_ != null)
                {
                    ServerMessage Message2 = new ServerMessage(915u);
                    Message2.AppendInt32(dataTable_.Rows.Count);
                    foreach (DataRow dataRow in dataTable_.Rows)
                    {
                        Group class3 = GroupManager.GetGroup((int)dataRow["groupid"]);
                        Message2.AppendInt32(class3.Id);
                        Message2.AppendStringWithBreak(class3.Name);
                        Message2.AppendStringWithBreak(class3.Badge);
                        if (Session.GetHabbo().GroupID == class3.Id)
                        {
                            Message2.AppendBoolean(true);
                        }
                        else
                        {
                            Message2.AppendBoolean(false);
                        }
                    }
                    Session.SendMessage(Message2);
                }
            }
        }
Example #21
0
        public void Execute(GameClients.GameClient Session, Rooms.Room Room, string[] Params)
        {
            #region Conditions
            if (!Session.GetRoleplay().IsWorking)
            {
                Session.SendWhisper("Você não está trabalhando!", 1);
                return;
            }

            if (Session.GetRoleplay().IsDead)
            {
                Session.SendWhisper("Você não pode parar de trabalhar enquanto está morto!", 1);
                return;
            }

            if (Session.GetRoleplay().IsJailed)
            {
                Session.SendWhisper("Você não pode parar de trabalhar enquanto está preso!", 1);
                return;
            }

            if (Session.GetRoleplay().TryGetCooldown("stopwork", true))
            {
                return;
            }

            #endregion

            if (GroupManager.HasJobCommand(Session, "guide"))
            {
                if (Session.GetRoleplay().GuideOtherUser != null)
                {
                    return;
                }

                Session.SendMessage(new HelperToolConfigurationComposer(Session));
                return;
            }

            WorkManager.RemoveWorkerFromList(Session);
            Session.GetRoleplay().IsWorking = false;
            Session.GetHabbo().Poof();
            Session.GetRoleplay().CooldownManager.CreateCooldown("stopwork", 1000, 10);
        }
Example #22
0
        public void OnPlayerDisconnected(Client player, byte type, string reason)
        {
            //Save data
            Character character = player.GetCharacter();

            if (character != null)
            {
                var account = player.GetAccount();

                if (account.AdminLevel > 0)
                {
                    foreach (var p in Players)
                    {
                        if (p.Client.GetAccount().AdminLevel > 0)
                        {
                            p.Client.SendChatMessage($"Admin {account.AdminName} has left the server.");
                        }
                    }
                }

                if (character.Group != Group.None)
                {
                    GroupManager.SendGroupMessage(player,
                                                  character.rp_name() + " from your group has left the server. (" + reason + ")");
                }

                account.Save();
                character.Save();

                //Stop all timers
                foreach (var timerVar in typeof(Character).GetProperties().Where(x => x.PropertyType == typeof(Timer)))
                {
                    var tim = (Timer)timerVar.GetValue(character);
                    tim?.Stop();
                }

                RemovePlayer(character);
                LogManager.Log(LogManager.LogTypes.Connection, $"{character.CharacterName}[{player.SocialClubName}] has left the server.");
            }
            else
            {
                LogManager.Log(LogManager.LogTypes.Connection, $"{player.SocialClubName} has left the server. (Not logged into a character)");
            }
        }
Example #23
0
        private string SyncHabMembers(HttpContext context)
        {
            string        strJsonResult = string.Empty;
            string        userAccount   = string.Empty;
            ErrorCodeInfo error         = new ErrorCodeInfo();
            Guid          transactionid = Guid.NewGuid();
            string        funname       = "SyncHabMembers";

            try
            {
                do
                {
                    string strAccesstoken = context.Request["accessToken"];
                    //判断AccessToken
                    if (string.IsNullOrEmpty(strAccesstoken))
                    {
                        error.Code    = ErrorCode.TokenEmpty;
                        strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
                        LoggerHelper.Info(userAccount, funname, context.Request.RawUrl, Convert.ToString(error.Code), false, transactionid);
                        break;
                    }

                    AdminInfo admin = new AdminInfo();
                    if (!TokenManager.ValidateUserToken(transactionid, strAccesstoken, out admin, out error))
                    {
                        strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
                        LoggerHelper.Info(userAccount, funname, context.Request.RawUrl, Convert.ToString(error.Code), false, transactionid);
                        break;
                    }

                    GroupManager manager = new GroupManager(ClientIP);
                    manager.SyncHabMembers(transactionid, admin, out strJsonResult);
                } while (false);
            }
            catch (Exception ex)
            {
                error.Code = ErrorCode.Exception;
                LoggerHelper.Error("HabGroup.ashx调用接口SyncHabMembers异常", context.Request.RawUrl, ex.ToString(), transactionid);
                LoggerHelper.Info(userAccount, funname, context.Request.RawUrl, Convert.ToString(error.Code), false, transactionid);
                strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
            }

            return(strJsonResult);
        }
Example #24
0
        public virtual object GetRootFolders(HttpContext context)
        {
            YZRequest request    = new YZRequest(context);
            int       groupid    = request.GetInt32("groupid", -1);
            string    folderType = request.GetString("folderType");
            string    uid        = YZAuthHelper.LoginUserAccount;

            FileSystem.FolderCollection rootFolders = new FileSystem.FolderCollection();

            using (IYZDbProvider provider = YZDbProviderManager.DefaultProvider)
            {
                using (IDbConnection cn = provider.OpenConnection())
                {
                    string filter = String.Format("FolderType=N'{0}'", provider.EncodeText(folderType));

                    LibraryCollection libs = LibraryManager.GetLibraries(provider, cn, uid, LibraryType.BPAFile.ToString(), null, null);
                    foreach (Library.Library lib in libs)
                    {
                        FileSystem.FolderCollection folders = FileSystem.DirectoryManager.GetFolders(provider, cn, lib.FolderID, filter, null);
                        foreach (FileSystem.Folder folder in folders)
                        {
                            folder.Name = lib.Name;
                        }

                        rootFolders.AddRange(folders);
                    }

                    if (groupid != -1)
                    {
                        Group.Group group = GroupManager.GetGroup(provider, cn, groupid);

                        FileSystem.FolderCollection folders = FileSystem.DirectoryManager.GetFolders(provider, cn, group.FolderID, filter, null);
                        foreach (FileSystem.Folder folder in folders)
                        {
                            folder.Name = group.Name;
                        }

                        rootFolders.AddRange(folders);
                    }
                }
            }

            return(rootFolders);
        }
Example #25
0
    public void GroupManager_Groups_With_Remanent()
    {
        GroupManager  manager  = new GroupManager();
        List <string> students = new List <string>()
        {
            "Samuel", "Lorenzo", "Mario", "Jonathan", "Leiscar", "Emily", "Julian"
        };

        int numberOfGroups = 4, groupsWithTwoStudents = 0, groupsWithOneStudent = 0, groupsWithOneSubject = 0, groupsWithTwoSubjects = 0;

        // 7 / 4 3 grupo de 2 y 1 grupo de 1
        // 6 / 4 2 grupos de 1 y 2 grupos de 2


        Group[] groups = manager.GetRandomizedGroups(students, subjects, numberOfGroups);


        foreach (var group in groups)
        {
            if (group.Students.Length == 1)
            {
                groupsWithOneStudent++;
            }
            else if (group.Students.Length == 2)
            {
                groupsWithTwoStudents++;
            }

            if (group.Subjects.Length == 1)
            {
                groupsWithOneSubject++;
            }
            else if (group.Subjects.Length == 2)
            {
                groupsWithTwoSubjects++;
            }
        }
        //ssds
        Assert.AreEqual(3, groupsWithTwoStudents);
        Assert.AreEqual(1, groupsWithOneStudent);
        Assert.AreEqual(2, groupsWithTwoSubjects);
        Assert.AreEqual(2, groupsWithOneSubject);
    }
Example #26
0
        public void Add(Group group, IEnumerable <Hash> hashes)
        {
            lock (_lockObject)
            {
                var groupManager = new GroupManager(group);

                _table[group] = groupManager;

                if (hashes == null)
                {
                    return;
                }

                foreach (var key in hashes)
                {
                    groupManager.Set(key, true);
                }
            }
        }
Example #27
0
        public void SendLobbyServerReadyNotification()
        {
            LobbyServerReadyNotification notification = new LobbyServerReadyNotification()
            {
                AccountData              = AccountManager.GetPersistedAccountData(this.AccountId),
                AlertMissionData         = new LobbyAlertMissionDataNotification(),
                CharacterDataList        = CharacterManager.GetCharacterDataList(this.AccountId),
                CommerceURL              = "http://127.0.0.1/AtlasCommerce",
                EnvironmentType          = EnvironmentType.External,
                FactionCompetitionStatus = new FactionCompetitionNotification(),
                FriendStatus             = FriendManager.GetFriendStatusNotification(this.AccountId),
                GroupInfo                = GroupManager.GetGroupInfo(this.AccountId),
                SeasonChapterQuests      = QuestManager.GetSeasonQuestDataNotification(),
                ServerQueueConfiguration = GetServerQueueConfigurationUpdateNotification(),
                Status = GetLobbyStatusNotification()
            };

            Send(notification);
        }
            public void SendsMessageToGroup()
            {
                // Arrange
                var connection = new Mock <IConnection>();

                connection.Setup(m => m.Send(It.IsAny <ConnectionMessage>()))
                .Callback <ConnectionMessage>(m =>
                {
                    Assert.Equal("Prefix.MyGroup", m.Signal);
                    Assert.Equal("some value", m.Value);
                    Assert.True(m.ExcludedSignals.Contains("x"));
                    Assert.True(m.ExcludedSignals.Contains("y"));
                });

                var groupManager = new GroupManager(connection.Object, "Prefix");

                // Act
                groupManager.Send("MyGroup", "some value", "x", "y");
            }
Example #29
0
        public async Task <ActionResult> UserGroups(SelectUserGroupsViewModel selGroups)
        {
            if (ModelState.IsValid)
            {
                var userGroups = await GroupManager.GetUserGroups(selGroups.UserId);

                var deletedGroupsIds = selGroups.Groups.Where(group => userGroups.Any(userGroup => userGroup.GroupId == group.GroupId && !group.IsSelected))
                                       .Select(group => group.GroupId);
                var newGroupsIds = selGroups.Groups.Where(group => !userGroups.Any(userGroup => userGroup.GroupId == group.GroupId)).Where(group => group.IsSelected)
                                   .Select(group => group.GroupId);

                await GroupManager.RemoveUserFromGroupAsync(selGroups.UserId, deletedGroupsIds);

                await GroupManager.AddUserToGroup(selGroups.UserId, newGroupsIds);

                return(RedirectToAction("UserList"));
            }
            return(View());
        }
Example #30
0
        public async Task <ActionResult> Details(string id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            var applicationgroup = await GroupManager.Groups.FirstOrDefaultAsync(g => g.Id == id);

            if (applicationgroup == null)
            {
                return(HttpNotFound());
            }
            var groupRoles = GroupManager.GetGroupRoles(applicationgroup.Id);
            var RoleNames  = groupRoles.Select(p => p.Name).ToArray();

            ViewBag.RolesList        = RoleNames;
            ViewBag.PermissionsCount = RoleNames.Count();
            return(View(applicationgroup));
        }
Example #31
0
        public async Task <ActionResult> GroupRoles(SelectGroupRolesViewModel selRoles)
        {
            if (ModelState.IsValid)
            {
                var groupRoles = await GroupManager.GetGroupRoles(selRoles.GroupId);

                var deletedRolesIds = selRoles.Roles.Where(role => groupRoles.Any(groupRole => groupRole.RoleId == role.RoleId && !role.IsSelected))
                                      .Select(role => role.RoleId);
                var newRolesIds = selRoles.Roles.Where(role => !groupRoles.Any(groupRole => groupRole.RoleId == role.RoleId)).Where(role => role.IsSelected)
                                  .Select(role => role.RoleId);

                await GroupManager.RemoveRolesFromGroupAsync(selRoles.GroupId, deletedRolesIds);

                await GroupManager.AddRoleToGroup(selRoles.GroupId, newRolesIds);

                return(RedirectToAction("GroupList"));
            }
            return(View());
        }
Example #32
0
        public async Task <IActionResult> Leave(string groupid)
        {
            // Get current user
            User user = await _userManager.GetUserAsync(User);

            // Ensure user is logged in
            if (user == null)
            {
                StatusMessage = $"Error: Please log in!";
                return(RedirectToAction("Index", controllerName: "Home"));
            }

            Group group = await _context.Groups.FindAsync(groupid);

            if (group == null)
            {
                StatusMessage = $"Error: Can't find group {groupid}!";
                return(RedirectToAction("Index", controllerName: "Home"));
            }

            if (!await group.IsInGroup(user))
            {
                StatusMessage = $"Error: You haven't joined {group.Name}!";
                return(RedirectToAction("Index", controllerName: "Home"));
            }

            if (group.IsOwner(user))
            {
                StatusMessage = $"Error: You cannot leave a group you own!";
                return(RedirectToAction("Index", controllerName: "Home"));
            }

            TaskResult result = await GroupManager.RemoveFromGroup(user, group);

            StatusMessage = result.Info;

            if (!result.Succeeded)
            {
                return(RedirectToAction("Index", controllerName: "Home"));
            }

            return(RedirectToAction(nameof(View), new { groupid = groupid }));
        }
Example #33
0
        public void Handle_NoGroups_DoesNothing()
        {
            // Arrange
            var handler = new RefreshGroupsHandler(Repo.Object, GroupManager.Object, UserService.Object);

            // Act
            handler.Handle();

            Repo.Verify(r => r.GetAll());
            Repo.Verify(r => r.GetAllUsers());

            GroupManager.Verify(u => u.GetUsersInGroup(It.IsAny <string>()), Times.Never);
            UserService.Verify(r => r.GetUserById(It.IsAny <int>()), Times.Never);
            Repo.Verify(r => r.DeleteUser(It.IsAny <int>()), Times.Never);
            UserService.Verify(u => u.Delete(It.IsAny <IUser>(), It.IsAny <bool>()), Times.Never);

            UserService.Verify(u => u.CreateUserWithIdentity(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <IUserType>()), Times.Never);
            UserService.Verify(u => u.Save(It.IsAny <IUser>(), It.IsAny <bool>()), Times.Never);
        }
Example #34
0
        private void AddGroups()
        {
            // Create bars group.
            barsGroup = new Group("Bars");
            barsGroup.Add("Pad", DataObjectType.String, 0);
            barsGroup.Add("SelectorKey", Instrument.Symbol);

            // Create fills group.
            fillGroup = new Group("Fills");
            fillGroup.Add("Pad", 0);
            fillGroup.Add("SelectorKey", Instrument.Symbol);

            // Create equity group.
            equityGroup = new Group("Equity");
            equityGroup.Add("Pad", 2);
            equityGroup.Add("SelectorKey", Instrument.Symbol);

            // Create RSI values group.
            rsiGroup = new Group("RSI");
            rsiGroup.Add("Pad", 1);
            rsiGroup.Add("SelectorKey", Instrument.Symbol);
            rsiGroup.Add("Color", Color.Blue);

            // Create BuyLevel values group.
            buyLevelGroup = new Group("BuyLevel");
            buyLevelGroup.Add("Pad", 1);
            buyLevelGroup.Add("SelectorKey", Instrument.Symbol);
            buyLevelGroup.Add("Color", Color.Red);

            // Create SellLevel values group.
            sellLevelGroup = new Group("SellLevel");
            sellLevelGroup.Add("Pad", 1);
            sellLevelGroup.Add("SelectorKey", Instrument.Symbol);
            sellLevelGroup.Add("Color", Color.Red);

            // Add groups to manager.
            GroupManager.Add(barsGroup);
            GroupManager.Add(fillGroup);
            GroupManager.Add(equityGroup);
            GroupManager.Add(rsiGroup);
            GroupManager.Add(buyLevelGroup);
            GroupManager.Add(sellLevelGroup);
        }
Example #35
0
        public async Task FetchByUserIdAsyncTest_WhenUserIdDoesntExists__ReturnsEmptyGroupResponseModel()
        {
            var groupMockRepository   = new Mock <IGroupRepository>();
            var mockThreadRepository  = new Mock <IThreadRepository>();
            var contactMockRepository = new Mock <IContactRepository>();
            var mapper      = GetMapperForGroupProfile();
            var groupEntity = EntityModellers.CreateGroupEntity();

            var userId   = _rnd.Next(111, 1000);
            var expected = mapper.Map <IEnumerable <GroupEntity>, IEnumerable <GroupResponseModel> >(new List <GroupEntity>());

            groupMockRepository.Setup(x => x.GetByUserIdAsync(userId)).ReturnsAsync((IEnumerable <GroupEntity>)null);

            var groupManager = new GroupManager(groupMockRepository.Object, mockThreadRepository.Object, mapper, contactMockRepository.Object);
            var actual       = await groupManager.FetchByUserIdAsync(userId);

            Assert.Equal(expected, actual, new LogicEqualityComparer <GroupResponseModel>());
            Assert.Empty(actual);
        }
Example #36
0
        private void AddGroups()
        {
            // Create bars group.
            barsGroup = new Group("Bars");
            barsGroup.Add("Pad", DataObjectType.String, 0);
            barsGroup.Add("SelectorKey", Instrument.Symbol);

            // Create fills group.
            fillGroup = new Group("Fills");
            fillGroup.Add("Pad", 0);
            fillGroup.Add("SelectorKey", Instrument.Symbol);

            // Create equity group.
            equityGroup = new Group("Equity");
            equityGroup.Add("Pad", 1);
            equityGroup.Add("SelectorKey", Instrument.Symbol);

            // Create BBU group.
            bbuGroup = new Group("BBU");
            bbuGroup.Add("Pad", 0);
            bbuGroup.Add("SelectorKey", Instrument.Symbol);
            bbuGroup.Add("Color", Color.Blue);

            // Create BBL group.
            bblGroup = new Group("BBL");
            bblGroup.Add("Pad", 0);
            bblGroup.Add("SelectorKey", Instrument.Symbol);
            bblGroup.Add("Color", Color.Blue);

            // Create SMA group.
            smaGroup = new Group("SMA");
            smaGroup.Add("Pad", 0);
            smaGroup.Add("SelectorKey", Instrument.Symbol);
            smaGroup.Add("Color", Color.Yellow);

            // Add groups to manager.
            GroupManager.Add(barsGroup);
            GroupManager.Add(fillGroup);
            GroupManager.Add(equityGroup);
            GroupManager.Add(bbuGroup);
            GroupManager.Add(bblGroup);
            GroupManager.Add(smaGroup);
        }
Example #37
0
            public void SendsMessageToGroup()
            {
                // Arrange
                var connection = new Mock<IConnection>();
                connection.Setup(m => m.Send(It.IsAny<ConnectionMessage>()))
                          .Callback<ConnectionMessage>(m =>
                          {
                              Assert.Equal("Prefix.MyGroup", m.Signal);
                              Assert.Equal("some value", m.Value);
                              Assert.True(m.ExcludedSignals.Contains("x"));
                              Assert.True(m.ExcludedSignals.Contains("y"));
                          });

                var groupManager = new GroupManager(connection.Object, "Prefix");

                // Act
                groupManager.Send("MyGroup", "some value", "x", "y");
            }
Example #38
0
        public override void Initialize()
        {
            HandleCommandLine(Environment.GetCommandLineArgs());
            //need to replace SavePath and use TPulsePath
            //HERE
            if (!Directory.Exists(SavePath))
                Directory.CreateDirectory(SavePath);

            DateTime now = DateTime.Now;
            string logFilename;
            try
            {
                //same has above
                logFilename = Path.Combine(SavePath, now.ToString(LogFormat)+".log");
            }
            catch(Exception)
            {
                // Problem with the log format use the default
                logFilename = Path.Combine(SavePath, now.ToString(LogFormatDefault) + ".log");
            }
            #if DEBUG
            Log.Initialize(logFilename, LogLevel.All, false);
            #else
            Log.Initialize(logFilename, LogLevel.All & ~LogLevel.Debug, LogClear);
            #endif
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            //wtf is this condition
            //if (Version.Major >= 4)
            //{
                showTPulseWelcome();
            //}

            try
            {
                //need to put pid file into constants
                if (File.Exists(TPulsePaths.GetPath(TPulsePath.ProcessFile)))
                {
                    Log.ConsoleInfo(
                        "TPulse was improperly shut down. Please use the exit command in the future to prevent this.");
                    File.Delete(TPulsePaths.GetPath(TPulsePath.ProcessFile));
                }
                File.WriteAllText(TPulsePaths.GetPath(TPulsePath.ProcessFile), Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture));

                ConfigFile.ConfigRead += OnConfigRead;
                FileTools.SetupConfig(this);

                HandleCommandLinePostConfigLoad(Environment.GetCommandLineArgs());

                if (Config.StorageType.ToLower() == "sqlite")
                {
                    string sql = TPulsePaths.GetPath(TPulsePath.SqliteFile);
                    DBConnection = new SqliteConnection(string.Format("uri=file://{0},Version=3", sql));
                }
                else if (Config.StorageType.ToLower() == "mysql")
                {
                    try
                    {
                        var hostport = Config.MySqlHost.Split(':');
                        DBConnection = new MySqlConnection();
                        DBConnection.ConnectionString =
                            String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};",
                                          hostport[0],
                                          hostport.Length > 1 ? hostport[1] : "3306",
                                          Config.MySqlDbName,
                                          Config.MySqlUsername,
                                          Config.MySqlPassword
                                );
                    }
                    catch (MySqlException ex)
                    {
                        Log.Error(ex.ToString());
                        throw new Exception("MySql not setup correctly");
                    }
                }
                else
                {
                    throw new Exception("Invalid storage type");
                }

                Backups = new BackupManager(TPulsePaths.GetPath(TPulsePath.BackupPath));
                Backups.KeepFor = Config.BackupKeepFor;
                Backups.Interval = Config.BackupInterval;
                Bans = new BanManager(DBConnection);
                Warps = new WarpManager(DBConnection);
                Regions = new RegionManager(DBConnection, this);
                Users = new UserManager(DBConnection, this);
                Groups = new GroupManager(DBConnection, this);
                Itembans = new ItemManager(DBConnection);
                RememberedPos = new RememberedPosManager(DBConnection);
                InventoryDB = new InventoryManager(DBConnection);
                RestApi = new SecureRest(Netplay.serverListenIP, Config.RestApiPort);
                RestApi.Verify += RestApi_Verify;
                RestApi.Port = Config.RestApiPort;
                RestManager = new RestManager(RestApi, this);
                RestManager.RegisterRestfulCommands();

                var geoippath = TPulsePaths.GetPath(TPulsePath.GeoIPFile);
                if (Config.EnableGeoIP && File.Exists(geoippath))
                    Geo = new GeoIPCountry(geoippath);

                Log.ConsoleInfo(string.Format("TPulse Version {0} ({1}) now running.", Version, VersionCodename));

                GameHooks.PostInitialize += OnPostInit;
                GameHooks.Update += OnUpdate;
                GameHooks.HardUpdate += OnHardUpdate;
                GameHooks.StatueSpawn += OnStatueSpawn;
                ServerHooks.Connect += OnConnect;
                ServerHooks.Join += OnJoin;
                ServerHooks.Leave += OnLeave;
                ServerHooks.Chat += OnChat;
                ServerHooks.Command += ServerHooks_OnCommand;
                NetHooks.GetData += OnGetData;
                NetHooks.SendData += NetHooks_SendData;
                NetHooks.GreetPlayer += OnGreetPlayer;
                NpcHooks.StrikeNpc += NpcHooks_OnStrikeNpc;
                NpcHooks.SetDefaultsInt += OnNpcSetDefaults;
                ProjectileHooks.SetDefaults += OnProjectileSetDefaults;
                WorldHooks.StartHardMode += OnStartHardMode;
                WorldHooks.SaveWorld += SaveManager.Instance.OnSaveWorld;
                WorldHooks.ChristmasCheck += OnXmasCheck;
                NetHooks.NameCollision += NetHooks_NameCollision;
                //World Saved hook
                GetDataHandlers.InitGetDataHandler();
                Commands.InitCommands();
                //RconHandler.StartThread();

                if (Config.RestApiEnabled)
                    RestApi.Start();

                if (Config.BufferPackets)
                    PacketBuffer = new PacketBufferer();

                Log.ConsoleInfo("AutoSave " + (Config.AutoSave ? "Enabled" : "Disabled"));
                Log.ConsoleInfo("Backups " + (Backups.Interval > 0 ? "Enabled" : "Disabled"));

                if (Initialized != null)
                    Initialized();
            }
            catch (Exception ex)
            {
                Log.Error("Fatal Startup Exception");
                Log.Error(ex.ToString());
                Environment.Exit(1);
            }
        }
Example #39
0
 public HubContext(Func<string, ClientHubInvocation, IEnumerable<string>, Task> send, string hubName, IConnection connection)
 {
     Clients = new ExternalHubConnectionContext(send, hubName);
     Groups = new GroupManager(connection, hubName);
 }
Example #40
0
 public HubContext(Func<string, ClientHubInvocation, IList<string>, Task> send, string hubName, IConnection connection)
 {
     Clients = new ExternalHubConnectionContext(send, hubName);
     Groups = new GroupManager(connection, PrefixHelper.GetHubGroupName(hubName));
 }
 public void Start()
 {
     gridScript = GameObject.Find("UGrid").GetComponent<UGrid>();
     groupM = GameObject.Find("Faction Manager").GetComponent<GroupManager>();
     placement = gameObject.GetComponent<BuildingPlacement>();
     if(placement)
         placement.SetGroup(group);
     GUIManager manager = gameObject.GetComponent<GUIManager>();
     if(manager)
         manager.group = groupM.groupList[group].GetComponent<Group>();
     guiManager = gameObject.GetComponent<GUIManager>();
     GameObject obj = GameObject.Find("MiniMap");
     if(obj)
         map = obj.GetComponent<MiniMap>();
     test = Camera.main.GetComponent<GUILayer>();
 }
            public void ThrowsIfGroupsIsNull()
            {
                // Arrange
                var connection = new Mock<IConnection>();
                connection.Setup(m => m.Send(It.IsAny<ConnectionMessage>()));
                var groupManager = new GroupManager(connection.Object, "Prefix");

                // Assert
                Assert.ThrowsAsync<ArgumentNullException>(() => groupManager.Send((IList<string>)null, "Way"));
            }
 public void SetupTest()
 {
     userManager = new BHUserManager(new UserStore<User>(BHDbContext.Create()));
     groupManager = new GroupManager();
 }
Example #44
0
		public void Setup()
		{
			gm = new GroupManager();
			person = new Person ("Id");
			group = new Group (1);
		}
 public void SetupTests()
 {
     //Database.SetInitializer(new MigrateDatabaseToLatestVersion<BHDbContext, Configuration>());
     //using (var _context = new BHDbContext())
     //    _context.Database.Initialize(true);
     groupManager = new GroupManager();
 }
Example #46
0
 public HubContext(IConnection connection, IHubPipelineInvoker invoker, string hubName)
 {
     Clients = new HubConnectionContextBase(connection, invoker, hubName);
     Groups = new GroupManager(connection, PrefixHelper.GetHubGroupName(hubName));
 }
 void OnGUI()
 {
     // Root GUI Display
     Vector2 defaultRect = new Vector2(1500, 750);
     Vector2 realRect = new Vector2(position.width, position.height);
     Vector2 rect = new Vector2((int)realRect.x/defaultRect.x, (int)realRect.y/defaultRect.y);
     if(!target){
         target = GameObject.Find("Faction Manager").GetComponent<GroupManager>();
         selectionTexture = target.selectionTexture;
     }
     helpState = 0;
     if(groupState == 0){
         DrawGroupGUI(rect);
     }
     else if(groupState == 1){
         if(unitState == 0){
             DrawUnitGUI(rect);
         }
         else{
             DrawBuildingGUI(rect);
         }
     }
     DrawSetup(rect);
 }
Example #48
0
    // Use this for initialization
    void Start()
    {
        current_state = 0;
        current_acceleration = max_speed;

        current_interval = 0f;
        if (behav == "")
        {
            behav = "Wander";
        }

        game_manager = GameObject.Find ("GameManager").GetComponent<GameManager> ();
        //
        gm = game_manager.gm;
        m = game_manager.m;
        Vector3 pos = this.transform.position;
        prev_location = new Vector4 (pos.x, pos.y, pos.z, 0);

        wander_dest.x = transform.position.x;
        wander_dest.y = transform.position.y;
        wander_dest.z = transform.position.z;
        target_go = null;

        anim = GetComponent<Animator>();
        controller = GetComponent<CharacterController>();
        prev_anim_speed = anim.speed;
        next_row = m.getRowNumber(this.transform.position.x);
        next_col = m.getColNumber(this.transform.position.z);
        if (behav == "Chase") {
            Vector3 my_pos = this.transform.position;
            target_path = PathPlanning.Plan (new Vector4(my_pos.x, my_pos.y, my_pos.z, current_state), prev_target_loc, m, strength, canTimeTravel);
        }
        if (!isPlayer) {
            m.updateInfluenceMap (new Vector4 (0, 0, 0, -1), prev_location, strength);
        }
    }