Exemplo n.º 1
0
        public void Should_not_send_second_message_to_group_as_it_does_not_exsist()
        {
            var message = "some message";
            var pipelineName = "A";
            var userGroup = MockRepository.GenerateMock<IUserGroup>();
            userGroup.Expect(x => x.Name).Return(pipelineName);
            userGroup.Expect(x => x.Send(message)).Repeat.Once();
            userGroup.Stub(x => x.Send(message)).Throw(new InvalidOperationException("Should not be called"));
            var projectMock = MockRepository.GenerateMock<IProject>();
            projectMock.Expect(x => x.PipelineName).Return(pipelineName);
            projectMock.Expect(x => x.GetMessage()).Return(message);

            buildCollection.Expect(x => x.ShouldAlert(projectMock)).Return(true).Repeat.Once();
            buildCollection.Expect(x => x.ShouldAlert(projectMock)).Return(false).Repeat.Once();

            var userGroups = new UserGroups(buildCollection);
            userGroups.Add(userGroup);
            //Test
            userGroups.Alert(projectMock);
            userGroups.Alert(projectMock);
            //Assert
            userGroup.VerifyAllExpectations();
            projectMock.VerifyAllExpectations();
            buildCollection.VerifyAllExpectations();
        }
        public UserGroupsResponse Post(UserGroups request)
        {
            if (request.UserGroup.Id > 0)
              {
            Bm2s.Data.Common.BLL.User.UserGroup item = Datas.Instance.DataStorage.UserGroups[request.UserGroup.Id];
            item.GroupId = request.UserGroup.Group.Id;
            item.UserId = request.UserGroup.User.Id;
            Datas.Instance.DataStorage.UserGroups[request.UserGroup.Id] = item;
              }
              else
              {
            Bm2s.Data.Common.BLL.User.UserGroup item = new Data.Common.BLL.User.UserGroup()
            {
              GroupId = request.UserGroup.Group.Id,
              UserId = request.UserGroup.User.Id
            };

            Datas.Instance.DataStorage.UserGroups.Add(item);
            request.UserGroup.Id = item.Id;
              }

              UserGroupsResponse response = new UserGroupsResponse();
              response.UserGroups.Add(request.UserGroup);
              return response;
        }
Exemplo n.º 3
0
 public void Should_return_true_for_single_monitor()
 {
     var someGroup = new UserGroup(null,null,"ShouldFind");
     var userGroup = new UserGroups(buildCollection);
     userGroup.Add(someGroup);
     Assert.That(userGroup.IsMonitoring("ShouldFind"), Is.EqualTo(true));
 }
Exemplo n.º 4
0
        public void Setup()
        {
            SnapshotInitialisation.ForceRestore();

            ICacheManager groupsCache = new StaticCacheManager();
            var g = new UserGroups(DnaMockery.CreateDatabaseReaderCreator(), DnaDiagnostics.Default, groupsCache,null, null);
            var b = new BannedEmails(DnaMockery.CreateDatabaseReaderCreator(), DnaDiagnostics.Default, groupsCache, null, null);
        }
Exemplo n.º 5
0
        public void Setup()
        {
            
            SnapshotInitialisation.ForceRestore();

            ICacheManager groupsCache = new StaticCacheManager();
            g = new UserGroups(DnaMockery.CreateDatabaseReaderCreator(), _context.dnaDiagnostics, groupsCache, null, null);
        }
        public UserGroupsResponse Delete(UserGroups request)
        {
            Bm2s.Data.Common.BLL.User.UserGroup item = Datas.Instance.DataStorage.UserGroups[request.UserGroup.Id];
              Datas.Instance.DataStorage.UserGroups.Remove(item);

              UserGroupsResponse response = new UserGroupsResponse();
              response.UserGroups.Add(request.UserGroup);
              return response;
        }
Exemplo n.º 7
0
        public void Initialise()
        {
            SnapshotInitialisation.RestoreFromSnapshot();
            SetupTestData();
            InitialiseMockedInputContext();

            var dnaDataReader = new DnaDataReaderCreator(DnaMockery.DnaConfig.ConnectionString);
            var usg = new UserGroups(dnaDataReader, _context.Diagnostics, CacheFactory.GetCacheManager("Memcached"),null, null);
        }
Exemplo n.º 8
0
        private Response GetUserGroups(dynamic args)
        {
            var groups = Async.Execute <List <UserGroup> >(() => UserGroups.GetUserGroups(args.app));

            var response = (Response)JsonConvert.SerializeObject(groups);

            response.ContentType = ResponseContentType;

            return(response);
        }
Exemplo n.º 9
0
 public void AddUserGroup(string username, UserGroups group)
 {
     if (UserAccountsDB.ContainsKey(username))
     {
         if (UserAccountsDB[username].IsAuthenticated)
         {
             UserAccountsDB[username].MemberOf.Add(group);
         }
     }
 }
Exemplo n.º 10
0
        protected void UserGroupList(ListControl chklUserGroupList)
        {
            IList <UserGroupsInfo> userGroupList = UserGroups.GetUserGroupList(0, 0);

            chklUserGroupList.Items.Clear();
            chklUserGroupList.DataSource     = userGroupList;
            chklUserGroupList.DataTextField  = "GroupName";
            chklUserGroupList.DataValueField = "GroupId";
            chklUserGroupList.DataBind();
        }
Exemplo n.º 11
0
 private void FillList()
 {
     UserGroups.RefreshCache();
     listGroups.Items.Clear();
     _listUserGroups = UserGroups.GetDeepCopy();
     for (int i = 0; i < _listUserGroups.Count; i++)
     {
         listGroups.Items.Add(_listUserGroups[i].Description);
     }
 }
Exemplo n.º 12
0
 public void InitializeOnStartup(bool refreshData, long userGroupNum, bool isPermissionMode, bool isCEMT = false)
 {
     _userGroupNum     = userGroupNum;
     _isPermissionMode = isPermissionMode;
     _isCEMT           = isCEMT;
     if (_isPermissionMode)
     {
         butUp.Visible          = false;
         butDown.Visible        = false;
         butSetAll.Visible      = true;
         comboUserGroup.Visible = true;
         labelUserGroup.Visible = true;
         label1.Text            = Lan.g(this, "The current selection's internal name is:");
     }
     else
     {
         butUp.Visible          = true;
         butDown.Visible        = true;
         butSetAll.Visible      = false;
         comboUserGroup.Visible = false;
         labelUserGroup.Visible = false;
         label1.Text            = Lan.g(this, "Move the selected item within its list.") + "\r\n" + Lan.g(this, "The current selection's internal name is:");
     }
     if (refreshData)
     {
         ListDisplayReportAll           = DisplayReports.GetAll(true);
         ListGroupPermissionsForReports = GroupPermissions.GetPermsForReports();
         ListGroupPermissionsOld        = new List <GroupPermission>();
         foreach (GroupPermission perm in ListGroupPermissionsForReports)
         {
             ListGroupPermissionsOld.Add(perm.Copy());
         }
         if (!isCEMT)
         {
             _listUserGroups = UserGroups.GetList();
         }
         else
         {
             _listUserGroups = UserGroups.GetList(true);
         }
         for (int i = 0; i < _listUserGroups.Count; i++)
         {
             comboUserGroup.Items.Add(_listUserGroups[i].Description);
             if (_listUserGroups[i].UserGroupNum == _userGroupNum)
             {
                 comboUserGroup.SelectedIndex = i;
             }
         }
         if (comboUserGroup.SelectedIndex == -1)
         {
             comboUserGroup.SelectedIndex = 0;
         }
     }
     FillGrids();
 }
Exemplo n.º 13
0
        public void InitInfo()
        {
            #region 初始化信息绑定
            targetforumid.BuildTree(Forums.GetForumListForDataTable(), "name", "fid");
            templateid.AddTableData(Templates.GetValidTemplateList(), "name", "templateid");

            DataTable dt = UserGroups.GetUserGroupForDataTable();
            int       i  = 1;
            foreach (DataRow dr in dt.Rows)
            {
                HtmlTableRow  tr = new HtmlTableRow();
                HtmlTableCell td = new HtmlTableCell("td");
                if (i % 2 == 1)
                {
                    td.Attributes.Add("class", "td_alternating_item1");
                }
                else
                {
                    td.Attributes.Add("class", "td_alternating_item2");
                }
                td.Controls.Add(new LiteralControl("<input type='checkbox' id='r" + i + "' onclick='selectRow(" + i + ",this.checked)'><label for='r" + i + "'>" + dr["grouptitle"].ToString() + "</lable>"));
                tr.Cells.Add(td);
                tr.Cells.Add(GetTD("viewperm", dr["groupid"].ToString(), i));
                tr.Cells.Add(GetTD("postperm", dr["groupid"].ToString(), i));
                tr.Cells.Add(GetTD("replyperm", dr["groupid"].ToString(), i));
                tr.Cells.Add(GetTD("getattachperm", dr["groupid"].ToString(), i));
                tr.Cells.Add(GetTD("postattachperm", dr["groupid"].ToString(), i));
                powerset.Rows.Add(tr);
                i++;
            }

            dt = Attachments.GetAttachmentType();
            attachextensions.AddTableData(dt);


            if (DNTRequest.GetString("fid") != "")
            {
                targetforumid.SelectedValue = DNTRequest.GetString("fid");
                addtype.SelectedValue       = "1";
                targetforumid.Visible       = true;
            }

            showcolnum.Attributes.Add("style", "display:none");
            colcount.SelectedIndex = 0;
            colcount.Attributes.Add("onclick", "javascript:document.getElementById('" + showcolnum.ClientID + "').style.display= (document.getElementById('TabControl1_tabPage51_colcount_0').checked ? 'none' : 'block');");

            showclose.Attributes.Add("style", "display:none");
            autocloseoption.SelectedIndex = 0;

            showtargetforum.Attributes.Add("style", "display:block");
            addtype.Attributes.Add("onclick", "javascript:document.getElementById('" + showtargetforum.ClientID + "').style.display= (document.getElementById('TabControl1_tabPage51_addtype_0').checked ? 'none' : 'block');setColDisplayer(document.getElementById('TabControl1_tabPage51_addtype_0').checked);");
            autocloseoption.Attributes.Add("onclick", "javascript:document.getElementById('" + showclose.ClientID + "').style.display= (document.getElementById('TabControl1_tabPage22_autocloseoption_0').checked ? 'none' : 'block');");

            #endregion
        }
Exemplo n.º 14
0
 public bool IsUserAuthorized(string username, UserGroups group)
 {
     if (UserAccountsDB.ContainsKey(username))
     {
         if (UserAccountsDB[username].HasRight(group))
         {
             return(true);
         }
     }
     return(false);
 }
        public UserGroups UpdateUserGroup(string id, UserGroups userGroups)
        {
            string query = "UPDATE `mentoringacademy`.`UserGroups` SET User_id='" + userGroups.User_id + "', Group_id='" + userGroups.Group_id + "' WHERE UG_id='" + id + "'";
            var    con   = new DBConnect();

            con.Update(query);

            return(userGroups);

            throw new NotImplementedException();
        }
        public UserGroups AddUserGroup(UserGroups userGroup)
        {
            string query = "INSERT INTO `mentoringacademy`.`UserGroups` (UG_id, User_id, Group_id) VALUES(" + userGroup.UG_id + "," + userGroup.User_id + "," + userGroup.Group_id + ")";
            var    con   = new DBConnect();

            con.Insert(query);

            return(userGroup);

            throw new NotImplementedException();
        }
Exemplo n.º 17
0
        public void StartUp()
        {
            Statistics.InitialiseIfEmpty(null,false);
            SnapshotInitialisation.RestoreFromSnapshot();


            ICacheManager groupsCache = new StaticCacheManager();
            var g = new UserGroups(DnaMockery.CreateDatabaseReaderCreator(), null, groupsCache, null, null);
            var p = new ProfanityFilter(DnaMockery.CreateDatabaseReaderCreator(), null, groupsCache, null, null);
            var b = new BannedEmails(DnaMockery.CreateDatabaseReaderCreator(), null, groupsCache, null, null);
        }
Exemplo n.º 18
0
        public IActionResult CreateModal()
        {
            var usrGr = new UserGroups();

            if (usrGr == null)
            {
                return(NotFound());
            }

            return(PartialView("EditModal", usrGr));
        }
Exemplo n.º 19
0
        public async Task <IActionResult> Join(int groupId, int parentSubjectId)
        {
            var currentUser = await this.GetCurrentUserAsync();

            var parentList = (await _context.Subjects
                              .Include(s => s.ParentList)
                              .ThenInclude(sl => sl.ExclusiveSubjectListsA)
                              .Include(s => s.ParentList)
                              .ThenInclude(sl => sl.ExclusiveSubjectListsB)
                              .FirstOrDefaultAsync(s => s.SubjectId == parentSubjectId)).ParentList;

            var exclusiveSubjectListsIds = parentList.ExclusiveSubjectListsA.Select(esl => esl.SubjectListBId)?.ToList();

            exclusiveSubjectListsIds.AddRange(parentList.ExclusiveSubjectListsB.Select(esl => esl.SubjectListAId));

            var exclusiveSubjectLists = _context.SubjectLists
                                        .Include(sl => sl.Subjects)
                                        .ThenInclude(s => s.Groups)
                                        .ThenInclude(g => g.UsersInGroup)
                                        .Where(sl => exclusiveSubjectListsIds.Contains(sl.SubjectListId) && sl.Subjects.Where(s => s.Groups.Where(g => g.UsersInGroup.Where(uig => uig.UserId == currentUser.Id).Select(uig => uig.GroupId).Contains(g.GroupId)).Select(g => g.SubjectId).Contains(s.SubjectId)).Select(s => s.ParentListId).Contains(sl.SubjectListId));

            if (!exclusiveSubjectLists.Any())
            {
                var userGroup = await _context.UserGroups?.FirstOrDefaultAsync(ug => ug.GroupId == groupId && ug.UserId == currentUser.Id);

                if (userGroup == null)
                {
                    var newUserGroup = new UserGroups()
                    {
                        GroupId = groupId,
                        UserId  = currentUser.Id,
                        User    = currentUser
                    };

                    if (ModelState.IsValid)
                    {
                        _context.Add(newUserGroup);
                        await _context.SaveChangesAsync();

                        return(RedirectToAction("Index", new { parentSubjectId = parentSubjectId }));
                    }
                }
                else
                {
                    return(RedirectToAction("Index", new { parentSubjectId = parentSubjectId }));
                }
            }


            //TODO
            //Tutaj wchodzi jak ModelState invalid, zmienic
            //return View();
            return(RedirectToAction(nameof(Error)));
        }
Exemplo n.º 20
0
        private void InitUserGroupCheckBoxList()
        {
            this.EChklUserGroupList.Items.Clear();
            IList <UserGroupsInfo> userGroupList = UserGroups.GetUserGroupList(0, 0);

            userGroupList.RemoveAt(0);
            this.EChklUserGroupList.DataSource     = userGroupList;
            this.EChklUserGroupList.DataTextField  = "GroupName";
            this.EChklUserGroupList.DataValueField = "GroupId";
            this.EChklUserGroupList.DataBind();
        }
Exemplo n.º 21
0
        public async Task <IActionResult> Create([Bind("Id,Name,Description")] UserGroups userGroups)
        {
            if (ModelState.IsValid)
            {
                _usrGrRepo.Add(userGroups);
                await _usrGrRepo.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(userGroups));
        }
        private void InitializeComponent()
        {
            this.BatchSendEmail.Click += new EventHandler(this.BatchSendEmail_Click);
            DataTable dt = UserGroups.GetUserGroupWithOutGuestTitle();

            foreach (DataRow dr in dt.Rows)
            {
                dr["grouptitle"] = "<img src=../images/usergroup.GIF border=0  style=\"position:relative;top:2 ;height:18 ;\">" + dr["grouptitle"];
            }
            Usergroups.AddTableData(dt);
        }
Exemplo n.º 23
0
        /// <summary>
        /// 重命名用户组
        /// </summary>
        /// <param name="group"></param>
        /// <param name="groupName"></param>
        public void RenameUserGroup(UserGroups group, string groupName)
        {
            dal.RenameUserGroup((int)group, groupName);

            //更新用户组的名称
            Array.ForEach(GetUserGroups(), a => { if (a.Id == (int)group)
                                                  {
                                                      a.Name = groupName;
                                                  }
                          });
        }
Exemplo n.º 24
0
 /// <summary>
 /// 增加用户信息
 /// </summary>
 /// <returns>成功否</returns>
 private bool AddUserGroupInfo()
 {
     if (AdminUserGroups.AddUserGroupInfo(userGroupInfo))
     {
         Discuz.Cache.DNTCache.GetCacheService().RemoveObject("/Forum/UserGroupList");
         UserGroups.GetUserGroupList();
         AdminVistLogs.InsertLog(this.userid, this.username, this.usergroupid, this.grouptitle, this.ip, "后台添加特殊用户组", "组名:" + groupTitle.Text);
         return(true);
     }
     return(false);
 }
Exemplo n.º 25
0
 public void BindData()
 {
     #region 绑定用户组列表
     DataGrid1.AllowCustomPaging = false;
     DataGrid1.TableHeaderName   = "用户组列表";
     DataGrid1.Attributes.Add("borderStyle", "2");
     DataGrid1.DataKeyField = "groupid";
     DataGrid1.BindData(UserGroups.GetCreditUserGroup());
     DataGrid1.Sort = "creditshigher";
     #endregion
 }
Exemplo n.º 26
0
        public void Login(string userName = null)
        {
            if (string.IsNullOrEmpty(userName))
            {
                userName = new UserGroups(this.Session).Administrators.Members.First.UserName;
            }

            this.Driver.Navigate().GoToUrl(Test.ClientUrl + "/login");
            var login = new LoginComponent(this.Driver);

            login.Login(userName);
        }
        public ajaxuserspacecommentlist()
        {
            postid = DNTRequest.GetInt("postid", 0);

            if (postid > 0)
            {
                if (Discuz.Common.DNTRequest.GetString("load") == "true")
                {
                    //当前用户是否是日志的作者
                    SpacePostInfo __spacepostinfo = BlogProvider.GetSpacepostsInfo(Space.Data.DbProvider.GetInstance().GetSpacePost(postid));
                    if (__spacepostinfo.Uid == userid)
                    {
                        ispostauthor = true;
                    }

                    if (Forum.AdminGroups.GetAdminGroupInfo(_userinfo.Groupid) != null)
                    {
                        isadmin = true;
                    }

                    //当是发布状态或当前作者的日志时
                    if (__spacepostinfo.PostStatus == 0)
                    {
                        errorinfo = "当前请求的内容无效!";
                        return;
                    }

                    //当有要删除的记录时
                    int delcommentid = DNTRequest.GetInt("delcommentid", 0);
                    if (delcommentid > 0)
                    {
                        //判断该用户是否为本人或管理组内
                        if ((UserGroups.GetUserGroupInfo(_userinfo.Groupid).Radminid == 1 && this.isadmin) || (this.spaceconfiginfo.UserID == this.userid))
                        {
                            Space.Data.DbProvider.GetInstance().DeleteSpaceComment(delcommentid);
                        }

                        //更新相关评论数
                        Space.Data.DbProvider.GetInstance().CountUserSpaceCommentCountByUserID(__spacepostinfo.Uid, -1);
                        Space.Data.DbProvider.GetInstance().CountSpaceCommentCountByPostID(postid, -1);
                    }

                    //得到当前评论列表
                    __spacecommentinfos = GetSpaceCommentInfoList(currentpage, postid);
                    //得到页码链接
                    pagelink = AjaxPagination(Space.Data.DbProvider.GetInstance().GetSpaceCommentsCountByPostid(postid), 16, currentpage);
                }
            }
            else
            {
                errorinfo = "当前请求日志回复信息无效!";
            }
        }
Exemplo n.º 28
0
        public async Task <ActionResult> OnGet()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(RedirectToPage("/Account/Login", new { area = "Identity" }));
            }
            try
            {
                var user = await _userManager.GetUserAsync(User);

                DefaultUserGroupID = await _siteData.GetDefaultUserGroupID(user.Id.ToString());

                if (DefaultUserGroupID == 0)
                {
                    if (HttpContext.Session.GetInt32("UserGroupID") == null)
                    {
                        UserGroups = await _siteData.GetUserGroups(user.Id.ToString());

                        int OwnUserGroupID = await _siteData.GetUserOwnGroup(user.Id.ToString());

                        for (int i = 0; i < UserGroups.Count(); i++)
                        {
                            if (OwnUserGroupID != UserGroups[i].UserGroupID)
                            {
                                return(RedirectToPage("WhichGroup"));
                            }
                            else
                            {
                                DefaultUserGroupID = OwnUserGroupID;
                                PotAccess          = await _siteData.GetPotAccess(user.Id.ToString(), DefaultUserGroupID);
                            }
                        }
                    }
                    else
                    {
                        CurrentUserGroupID = HttpContext.Session.GetInt32("UserGroupID");
                        DefaultUserGroupID = CurrentUserGroupID;
                        PotAccess          = await _siteData.GetPotAccess(user.Id.ToString(), CurrentUserGroupID);

                        return(Page());
                    }
                }
                PotAccess = await _siteData.GetPotAccess(user.Id.ToString(), DefaultUserGroupID);

                HttpContext.Session.SetInt32("UserGroupID", DefaultUserGroupID.Value);
                return(Page());
            }
            catch (Exception ex)
            {
                Log.Error(ex.ToString());
                throw new Exception(ex.ToString());
            }
        }
Exemplo n.º 29
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            if (UserGroups.Any() == false)
            {
                yield return(new ValidationResult("A user must be assigned to at least one group", new[] { "UserGroups" }));
            }

            if (Current.Configs.Settings().Security.UsernameIsEmail == false && Username.IsNullOrWhiteSpace())
            {
                yield return(new ValidationResult("A username cannot be empty", new[] { "Username" }));
            }
        }
Exemplo n.º 30
0
 public Response <UserGroups> UpdateUserGroups([FromBody] UserGroups usergroup)
 {
     try
     {
         return(_userGroupBusiness.UpdateUserGroups(usergroup));
     }
     catch (Exception e)
     {
         _logger.Error($"UpdateUserGroups Failed: {e.Message}\n {e.StackTrace}");
         return(new Response <UserGroups>(false, e.Message, null));
     }
 }
Exemplo n.º 31
0
        /// <summary>
        /// Update the state of the wrapper to reflect the current network configuration and state
        /// </summary>
        /// <returns></returns>
        public async Task Refresh()
        {
            await Task.WhenAll(
                Clients.Refresh(),
                InfrastructureDevices.Refresh(),
                WlanGroups.Refresh(),
                UserGroups.Refresh(),
                PortForwards.Refresh()
                );

            InferConvergedTopology();
        }
 public void Clear()
 {
     Name     = null;
     Login    = null;
     Password = null;
     if (UserGroups != null)
     {
         UserGroups.Clear();
     }
     Enabled     = true;
     CreatedDate = null;
 }
Exemplo n.º 33
0
        protected void Application_Start(object sender, EventArgs e)
        {
            //System.Diagnostics.Debugger.Launch();
            if (ConfigurationManager.AppSettings["MaintenanceMode"] == "1")
            {//do nothing if in maintenance
                return;
            }

            Statistics.InitialiseIfEmpty(null, false);
            dnaDiagnostics = new DnaDiagnostics(RequestIdGenerator.GetNextRequestId(), DateTime.Now);
            connectionString = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
            readerCreator = new DnaDataReaderCreator(connectionString, dnaDiagnostics);

            try
            {
                emailServerAddress = ConfigurationManager.AppSettings["EmailServer"];
            }
            catch
            {
                dnaDiagnostics.WriteWarningToLog("BBC.Dna.Services.Application_Start", "Unable to find config email server address - no emails will be sent!");
            }

            try
            {
                fileCacheFolder = ConfigurationManager.AppSettings["FileCacheFolder"];
            }
            catch
            {
                fileCacheFolder = Environment.GetEnvironmentVariable("Temp");
                dnaDiagnostics.WriteWarningToLog("BBC.Dna.Services.Application_Start", "Unable to find config file cache folder - Defaulting to the system temp folder!");
            }

            ICacheManager cacheManager = null;
            try
            {
                cacheManager = CacheFactory.GetCacheManager("Memcached");
            }
            catch (Exception error)
            {
                dnaDiagnostics.WriteWarningToLog("BBC.Dna.Services.Application_Start", "Unable to use memcached cachemanager - falling back to static inmemory");
                dnaDiagnostics.WriteExceptionToLog(error);
                cacheManager = new StaticCacheManager();
            }


            siteList = new SiteList(readerCreator, dnaDiagnostics, cacheManager, null, null);//no sending signals from here
            var bannedEmails = new BannedEmails(readerCreator, dnaDiagnostics, cacheManager, null, null);//no sending signals from here
            var userGroups = new UserGroups(readerCreator, dnaDiagnostics, cacheManager, null, null);//no sending signals from here
            var profanityFilter = new ProfanityFilter(readerCreator, dnaDiagnostics, cacheManager, null, null);//no sending signals from here
            var moderationClasses = new ModerationClassListCache(readerCreator, dnaDiagnostics, cacheManager, null, null);//no sending signals from here
            BBC.Dna.Objects.SmileyTranslator.LoadSmileys(readerCreator);
        }
Exemplo n.º 34
0
        private void radminid_SelectedIndexChanged(object sender, EventArgs e)
        {
            #region 绑定关联组
            //DataTable usergrouprightstable = Discuz.Data.DatabaseProvider.GetInstance().GetUserGroupInfoByGroupid(int.Parse(radminid.SelectedValue));
            UserGroupInfo radminUserGroupInfo = UserGroups.GetUserGroupInfo(int.Parse(radminid.SelectedValue));
            if (radminUserGroupInfo != null)
            {
                //设置管理组初始化信息
                //DataRow usergrouprights = usergrouprightstable.Rows[0];
                creditshigher.Text = radminUserGroupInfo.Creditslower.ToString();
                creditslower.Text  = radminUserGroupInfo.Creditslower.ToString();
                stars.Text         = radminUserGroupInfo.Stars.ToString();
                color.Text         = radminUserGroupInfo.Color;
                groupavatar.Text   = radminUserGroupInfo.Groupavatar;
                readaccess.Text    = radminUserGroupInfo.Readaccess.ToString();
                maxprice.Text      = radminUserGroupInfo.Maxprice.ToString();
                maxpmnum.Text      = radminUserGroupInfo.Maxpmnum.ToString();
                maxsigsize.Text    = radminUserGroupInfo.Maxsigsize.ToString();
                maxattachsize.Text = radminUserGroupInfo.Maxattachsize.ToString();
                maxsizeperday.Text = radminUserGroupInfo.Maxsizeperday.ToString();
                DataTable dt = Attachments.GetAttachmentType();
                attachextensions.AddTableData(dt, radminUserGroupInfo.Attachextensions);
            }

            AdminGroupInfo radminUserGroup = AdminGroups.GetAdminGroupInfo(int.Parse(radminid.SelectedValue));
            if (radminUserGroup != null)
            {
                //设置管理权限组初始化信息
                //DataRow dr = admingrouprights.Rows[0];
                admingroupright.SelectedIndex     = -1;
                admingroupright.Items[0].Selected = radminUserGroup.Alloweditpost == 1;
                admingroupright.Items[1].Selected = radminUserGroup.Alloweditpoll == 1;
                admingroupright.Items[2].Selected = radminUserGroup.Allowdelpost == 1;
                admingroupright.Items[3].Selected = radminUserGroup.Allowmassprune == 1;
                admingroupright.Items[4].Selected = radminUserGroup.Allowviewip == 1;
                admingroupright.Items[5].Selected = radminUserGroup.Allowedituser == 1;
                admingroupright.Items[6].Selected = radminUserGroup.Allowviewlog == 1;
                admingroupright.Items[7].Selected = radminUserGroup.Disablepostctrl == 1;
                admingroupright.Items[8].Selected = radminUserGroup.Allowviewrealname == 1;
            }

            if (radminid.SelectedValue == "1")
            {
                allowstickthread.Enabled       = false;
                allowstickthread.SelectedValue = "3";
            }
            else
            {
                allowstickthread.Enabled = true;
            }
            #endregion
        }
        public JsonResult AddGroup(string groupName)
        {
            Groups     group;
            UserGroups userGroup;
            int        userId = Convert.ToInt32(Session[Sys.userId]);

            try
            {
                using (entities = new wwbEntities())
                {
                    /* If group not exist then insert then just take id below */
                    group = entities.Groups
                            .Where(g => g.group_name == groupName)
                            .FirstOrDefault();

                    if (group == null)
                    {
                        group            = new Groups();
                        group.group_name = groupName;

                        entities.Groups.Add(group);
                        entities.SaveChanges();
                    }
                }
                using (entities = new wwbEntities())
                {
                    /* Already exists */ //TODO : There is possibly a problem. check it
                    userGroup = entities.UserGroups
                                .Where(ug => (ug.user_id == userId && ug.group_id == group.group_id))
                                .FirstOrDefault();

                    if (userGroup != null)
                    {
                        return(Json(GroupAddingStatus.AlreadyExist, JsonRequestBehavior.AllowGet));
                    }

                    userGroup          = new UserGroups();
                    userGroup.group_id = group.group_id;
                    userGroup.user_id  = userId;

                    entities.UserGroups.Add(userGroup);
                    entities.SaveChanges();
                }
            }
            catch (Exception e)
            {
                return(Json(GroupAddingStatus.Fail, JsonRequestBehavior.AllowGet));
            }


            return(Json(GroupAddingStatus.Success, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 36
0
        public async Task <bool> RemoveUserFromGroup(AppUserId appUserId, CancellationToken cancellationToken = default)
        {
            var userGroup = UserGroups.SingleOrDefault(x => x.AppUserId == appUserId);

            if (userGroup == null)
            {
                return(false);
            }

            UserGroups.Remove(userGroup);

            return(true);
        }
Exemplo n.º 37
0
        private void ChklUserGroupListBind()
        {
            IList <UserGroupsInfo> userGroupList = UserGroups.GetUserGroupList(0, 0);

            if (userGroupList.Count > 0)
            {
                this.ChklUserGroupList.Items.Clear();
                this.ChklUserGroupList.DataSource     = userGroupList;
                this.ChklUserGroupList.DataTextField  = "GroupName";
                this.ChklUserGroupList.DataValueField = "GroupId";
                this.ChklUserGroupList.DataBind();
            }
        }
Exemplo n.º 38
0
        public void Should_return_true_for_multiple_monitors()
        {
            var someGroup = new UserGroup(null, null, "A");
            var someGroup1 = new UserGroup(null, null, "B");
            var someGroup2 = new UserGroup(null, null, "C");

            var userGroup = new UserGroups(buildCollection);
            userGroup.Add(someGroup);
            userGroup.Add(someGroup1);
            userGroup.Add(someGroup2);
            Assert.That(userGroup.IsMonitoring("A"), Is.EqualTo(true));
            Assert.That(userGroup.IsMonitoring("C"), Is.EqualTo(true));
        }
Exemplo n.º 39
0
        /// <summary>
        /// Constructor
        /// </summary>
        public RatingForumTests()
        {
            using (FullInputContext inputcontext = new FullInputContext(""))
            {
                _siteList = SiteList.GetSiteList();
                site = _siteList.GetSite("h2g2");

                _ratings = new Reviews(inputcontext.dnaDiagnostics, inputcontext.ReaderCreator, CacheFactory.GetCacheManager(), _siteList);
                var b = new BannedEmails(inputcontext.ReaderCreator, inputcontext.dnaDiagnostics, CacheFactory.GetCacheManager(), null, null);
                var g = new UserGroups(inputcontext.ReaderCreator, inputcontext.dnaDiagnostics, CacheFactory.GetCacheManager(), null, null);
            }
            
        }
Exemplo n.º 40
0
 private void InitRoleCheckBoxList()
 {
     this.EChkGroupList.Items.Clear();
     this.EChkGroupList.DataSource     = UserGroups.GetUserGroupList(0, 0);
     this.EChkGroupList.DataTextField  = "GroupName";
     this.EChkGroupList.DataValueField = "GroupId";
     this.EChkGroupList.DataBind();
     this.EChkRoleList.Items.Clear();
     this.EChkRoleList.DataSource     = UserRole.GetRoleList();
     this.EChkRoleList.DataTextField  = "RoleName";
     this.EChkRoleList.DataValueField = "RoleId";
     this.EChkRoleList.DataBind();
 }
Exemplo n.º 41
0
        protected override void OnSaveEventHandler(VmOnSave obj)
        {
            var row = obj.GetRow <UserGroup>();

            if (row != null)
            {
                UserGroups.Add((UserGroup)row);
            }
            else
            {
                base.OnSaveEventHandler(obj);
            }
        }
Exemplo n.º 42
0
 public void StartUp()
 {
     SnapshotInitialisation.RestoreFromSnapshot();
     Statistics.InitialiseIfEmpty(null, false);
     using (FullInputContext inputcontext = new FullInputContext(""))
     {
         var p = new ProfanityFilter(DnaMockery.CreateDatabaseReaderCreator(), null, CacheFactory.GetCacheManager(), null, null);
         var b = new BannedEmails(DnaMockery.CreateDatabaseReaderCreator(), null, CacheFactory.GetCacheManager(), null, null);
         var g = new UserGroups(DnaMockery.CreateDatabaseReaderCreator(), null, CacheFactory.GetCacheManager(), null, null);
         _siteList = SiteList.GetSiteList();
         site = _siteList.GetSite("h2g2");
         site.IsEmergencyClosed = false;
         _ratings = new Reviews(inputcontext.dnaDiagnostics, inputcontext.ReaderCreator, CacheFactory.GetCacheManager(), _siteList);
     }
 }
Exemplo n.º 43
0
        public UserGroupsResponse Get(UserGroups request)
        {
            UserGroupsResponse response = new UserGroupsResponse();
              List<Bm2s.Data.Common.BLL.User.UserGroup> items = new List<Data.Common.BLL.User.UserGroup>();
              if (!request.Ids.Any())
              {
            items.AddRange(Datas.Instance.DataStorage.UserGroups.Where(item =>
              (request.GroupId == 0 || item.GroupId == request.GroupId) &&
              (request.UserId == 0 || item.UserId == request.UserId)
              ));
              }
              else
              {
            items.AddRange(Datas.Instance.DataStorage.UserGroups.Where(item => request.Ids.Contains(item.Id)));
              }

              var collection = (from item in items
                        select new Bm2s.Poco.Common.User.UserGroup()
                        {
                          Group = new GroupsService().Get(new Groups() { Ids = new List<int>() { item.GroupId } }).Groups.FirstOrDefault(),
                          Id = item.Id,
                          User = new UsersService().Get(new Users() { Ids = new List<int>() { item.UserId } }).Users.FirstOrDefault()
                        }).AsQueryable().OrderBy(request.Order, !request.DescendingOrder);

              response.ItemsCount = collection.Count();
              if (request.PageSize > 0)
              {
            response.UserGroups.AddRange(collection.Skip((request.CurrentPage - 1) * request.PageSize).Take(request.PageSize));
              }
              else
              {
            response.UserGroups.AddRange(collection);
              }

              try
              {
            response.PagesCount = collection.Count() / response.UserGroups.Count + (collection.Count() % response.UserGroups.Count > 0 ? 1 : 0);
              }
              catch
              {
            response.PagesCount = 1;
              }

              return response;
        }
Exemplo n.º 44
0
        public void InitialiseAllUsersAndGroups_ValidDataSet_ReturnsCorrectObject()
        {
            var groupName = "editor";
            var siteId = new Queue<int>();
            siteId.Enqueue(1);
            siteId.Enqueue(2);
            siteId.Enqueue(2);
            var userId = new Queue<int>();
            userId.Enqueue(6);
            userId.Enqueue(6);
            userId.Enqueue(7);

            var cache = _mocks.DynamicMock<ICacheManager>();
            cache.Stub(x => x.Contains("")).Constraints(Is.Anything()).Return(false);

            var readerMembers = _mocks.DynamicMock<IDnaDataReader>();
            readerMembers.Stub(x => x.Read()).Return(true).Repeat.Times(3);
            readerMembers.Stub(x => x.GetString("name")).Return(groupName);
            readerMembers.Stub(x => x.GetInt32("siteid")).Return(1).WhenCalled(x => x.ReturnValue = siteId.Dequeue());
            readerMembers.Stub(x => x.GetInt32("userid")).Return(1).WhenCalled(x => x.ReturnValue = userId.Dequeue());

            var readerGetAllGroups = _mocks.DynamicMock<IDnaDataReader>();
            readerGetAllGroups.Stub(x => x.Read()).Return(true).Repeat.Once();
            readerGetAllGroups.Stub(x => x.GetString("groupname")).Return(groupName);

            var creator = _mocks.DynamicMock<IDnaDataReaderCreator>();
            creator.Stub(x => x.CreateDnaDataReader("fetchgroupsandmembersbysite")).Return(readerMembers);
            creator.Stub(x => x.CreateDnaDataReader("GetAllGroups")).Return(readerGetAllGroups);
            

            var diag = _mocks.DynamicMock<IDnaDiagnostics>();
            _mocks.ReplayAll();

            var obj = new UserGroups(creator, diag, cache, null, null);

            var cachedObj = UserGroups.GetObject().InternalObjects;
            Assert.IsNotNull(cachedObj);
            Assert.AreEqual(6, cachedObj.Count);
            Assert.IsTrue(cachedObj.ContainsKey(UserGroups.CreateCacheKey(1)));

            var groupsList = (List<UserGroup>)cachedObj[UserGroups.GetCacheKey(UserGroups.ALLGROUPSKEY)];
            Assert.AreEqual(1, groupsList.Count);
            Assert.AreEqual(groupName, groupsList[0].Name);

        }
Exemplo n.º 45
0
        public void StartUp()
        {
            SnapshotInitialisation.ForceRestore();
            Statistics.InitialiseIfEmpty();

            using (FullInputContext inputcontext = new FullInputContext(""))
            {
                _siteList = SiteList.GetSiteList();
                site = _siteList.GetSite("h2g2");

                _comments = new Comments(inputcontext.dnaDiagnostics, inputcontext.ReaderCreator, CacheFactory.GetCacheManager(), _siteList);
                
                ICacheManager groupsCache = new StaticCacheManager();
                var g = new UserGroups(DnaMockery.CreateDatabaseReaderCreator(), null, groupsCache, null, null);
                var p = new ProfanityFilter(DnaMockery.CreateDatabaseReaderCreator(), null, groupsCache, null, null);
                var b = new BannedEmails(DnaMockery.CreateDatabaseReaderCreator(), null, groupsCache, null, null);
            }
        }
Exemplo n.º 46
0
        public void StartUp()
        {
            SnapshotInitialisation.RestoreFromSnapshot();
            Statistics.InitialiseIfEmpty(null,false);
            Statistics.ResetCounters();

            using (FullInputContext inputcontext = new FullInputContext(""))
            {
                using (IDnaDataReader reader = inputcontext.CreateDnaDataReader(""))
                {//force processpremod out...
                    reader.ExecuteDEBUGONLY("delete from siteoptions where SiteID=1 and Name='ProcessPreMod'");
                }
                _siteList = SiteList.GetSiteList();
                site = _siteList.GetSite("h2g2");

                _comments = new Comments(inputcontext.dnaDiagnostics, inputcontext.ReaderCreator, CacheFactory.GetCacheManager(), _siteList);
                var bannedEmails = new BannedEmails(inputcontext.ReaderCreator, inputcontext.dnaDiagnostics, CacheFactory.GetCacheManager(), null, null);//no sending signals from here
                var userGroups = new UserGroups(inputcontext.ReaderCreator, inputcontext.dnaDiagnostics, CacheFactory.GetCacheManager(), null, null);//no sending signals from here
                var profanityFilter = new ProfanityFilter(inputcontext.ReaderCreator, inputcontext.dnaDiagnostics, CacheFactory.GetCacheManager(), null, null);//no sending signals from here            
            }
        }
Exemplo n.º 47
0
        public void Should_not_send_message_to_group_as_it_does_not_exsist()
        {
            var message = "some message";
            var pipelineName = "A";
            var userGroup = MockRepository.GenerateMock<IUserGroup>();
            userGroup.Expect(x => x.Name).Return(pipelineName);
            userGroup.AssertWasNotCalled(x => x.Send(message));

            var projectMock = MockRepository.GenerateMock<IProject>();
            projectMock.Expect(x => x.PipelineName).Return("not found");

            var userGroups = new UserGroups(buildCollection );
            userGroups.Add(userGroup);

            //Test
            userGroups.Alert(projectMock);

            //Assert
            userGroup.VerifyAllExpectations();
            projectMock.VerifyAllExpectations();
        }
Exemplo n.º 48
0
        public void HandleSignal_RefreshAllUsersAndGroups_CorrectlyHandlesSignal()
        {
            var userId = 7;
            var siteId = 2;
            var signalType = "recache-groups";

            var groupName = "editor";
            var siteIds = new Queue<int>();
            siteIds.Enqueue(1);
            siteIds.Enqueue(2);
            siteIds.Enqueue(2);
            var userIds = new Queue<int>();
            userIds.Enqueue(6);
            userIds.Enqueue(6);
            userIds.Enqueue(7);

            var cache = GetGroupsCache(_mocks);

            var readerMembers = _mocks.DynamicMock<IDnaDataReader>();
            readerMembers.Stub(x => x.Read()).Return(true).Repeat.Times(3);
            readerMembers.Stub(x => x.GetString("name")).Return(groupName);
            readerMembers.Stub(x => x.GetInt32("siteid")).Return(1).WhenCalled(x => x.ReturnValue = siteIds.Dequeue());
            readerMembers.Stub(x => x.GetInt32("userid")).Return(1).WhenCalled(x => x.ReturnValue = userIds.Dequeue());

            var readerGetAllGroups = _mocks.DynamicMock<IDnaDataReader>();
            readerGetAllGroups.Stub(x => x.Read()).Return(true).Repeat.Once();
            readerGetAllGroups.Stub(x => x.GetString("groupname")).Return(groupName);

            var creator = _mocks.DynamicMock<IDnaDataReaderCreator>();
            creator.Stub(x => x.CreateDnaDataReader("fetchgroupsandmembersbysite")).Return(readerMembers);
            creator.Stub(x => x.CreateDnaDataReader("GetAllGroups")).Return(readerGetAllGroups);

            var diag = _mocks.DynamicMock<IDnaDiagnostics>();
            _mocks.ReplayAll();

            var obj = new UserGroups(creator, diag, cache, null, null);

            Assert.IsTrue(obj.HandleSignal(signalType, null));
            var cacheKey = UserGroups.CreateCacheKey(siteId);
            Assert.AreEqual(1, ((UserSiteGroups)obj.InternalObjects[cacheKey]).UserGroupIds[userId].Count);
        }
Exemplo n.º 49
0
 /// <summary>
 /// 更新用户资料
 /// </summary>
 /// <param name="username"></param>
 /// <param name="name"></param>
 /// <param name="group"></param>
 /// <param name="available"></param>
 public void UpdateUser(string username, int siteid, string name, UserGroups group, bool available)
 {
     dal.UpdateUser(username, siteid, name, (int)group, available);
 }
Exemplo n.º 50
0
        /// <summary>
        /// 更新用户组的权限
        /// </summary>
        /// <param name="group"></param>
        /// <param name="permissions"></param>
        public void UpdateUserGroupPermissions(UserGroups group, Operation[] permissions)
        {
            dal.UpdateUserGroupPermissions((int)group, ConvertPermissionArrayToString(permissions));

            //更新组的权限
            if (groups == null) GetUserGroups();
            Array.ForEach(groups, a => { if (a.ID == (int)group)a.Permissions = permissions; });
        }
Exemplo n.º 51
0
        /// <summary>
        /// 重命名用户组
        /// </summary>
        /// <param name="group"></param>
        /// <param name="groupName"></param>
        public void RenameUserGroup(UserGroups group, string groupName)
        {
           dal.RenameUserGroup((int)group, groupName);

            //更新用户组的名称
            Array.ForEach(GetUserGroups(), a => { if (a.ID == (int)group)a.Name = groupName; });

        }
Exemplo n.º 52
0
        public void HandleSignal_RefreshSingleUsersGroups_CorrectlyHandlesSignal()
        {
            var userId = 6;
            var siteId = 3;
            var signalType = "recache-groups";

            var groupName = "editor";
            var siteIds = new Queue<int>();
            siteIds.Enqueue(1);
            siteIds.Enqueue(2);
            siteIds.Enqueue(siteId);
            var userIds = new Queue<int>();
            userIds.Enqueue(6);
            userIds.Enqueue(6);
            userIds.Enqueue(userId);

            var siteId2s = new Queue<int>();
            siteId2s.Enqueue(1);
            siteId2s.Enqueue(2);
            siteId2s.Enqueue(3);
            var userId2s = new Queue<int>();
            userId2s.Enqueue(userId);
            userId2s.Enqueue(userId);
            userId2s.Enqueue(userId);

            var cache = GetGroupsCache(_mocks);

            var readerMembers = _mocks.DynamicMock<IDnaDataReader>();
            readerMembers.Stub(x => x.Read()).Return(true).Repeat.Times(3);
            readerMembers.Stub(x => x.GetString("name")).Return(groupName);
            readerMembers.Stub(x => x.GetInt32("siteid")).Return(1).WhenCalled(x => x.ReturnValue = siteIds.Dequeue());
            readerMembers.Stub(x => x.GetInt32("userid")).Return(1).WhenCalled(x => x.ReturnValue = userIds.Dequeue());

            var readerGetAllGroups = _mocks.DynamicMock<IDnaDataReader>();
            readerGetAllGroups.Stub(x => x.Read()).Return(true).Repeat.Once();
            readerGetAllGroups.Stub(x => x.GetString("groupname")).Return(groupName);

            

            var readerGetUserGroups = _mocks.DynamicMock<IDnaDataReader>();
            readerGetUserGroups.Stub(x => x.Read()).Return(true).Repeat.Times(3);
            readerGetUserGroups.Stub(x => x.GetString("name")).Return(groupName);
            readerGetUserGroups.Stub(x => x.GetInt32("siteid")).Return(1).WhenCalled(x => x.ReturnValue = siteId2s.Dequeue());
            readerGetUserGroups.Stub(x => x.GetInt32("userid")).Return(1).WhenCalled(x => x.ReturnValue = userId2s.Dequeue());


            var creator = _mocks.DynamicMock<IDnaDataReaderCreator>();
            creator.Stub(x => x.CreateDnaDataReader("fetchgroupsandmembersbysite")).Return(readerMembers);
            creator.Stub(x => x.CreateDnaDataReader("GetAllGroups")).Return(readerGetAllGroups);
            creator.Stub(x => x.CreateDnaDataReader("fetchgroupsforuser")).Return(readerGetUserGroups);

            var diag = _mocks.DynamicMock<IDnaDiagnostics>();
            _mocks.ReplayAll();

            var obj = new UserGroups(creator, diag, cache, null, null);

            Assert.AreEqual(2, obj.InternalObjects.Count);

            NameValueCollection args = new NameValueCollection();
            args.Add("userid", userId.ToString());
            Assert.IsTrue(obj.HandleSignal(signalType, args));
            //none returned as refresh removed all existing groups
            Assert.AreEqual(8, obj.InternalObjects.Count);
            var cacheKey = UserGroups.CreateCacheKey(siteId);
            Assert.AreEqual(1, ((UserSiteGroups)obj.InternalObjects[cacheKey]).UserGroupIds[userId].Count);
        }
Exemplo n.º 53
0
 /// <summary>
 /// 获取用户组
 /// </summary>
 /// <param name="group"></param>
 /// <returns></returns>
 public UserGroup GetUserGroup(UserGroups group)
 {
     UserGroup[] groups = GetUserGroups();
     if (groups != null)
     {
         foreach (UserGroup u in groups)
         {
             if (u != null && u.ID == (int) group)
             {
                 return u;
             }
         }
     }
     return null;
 }
Exemplo n.º 54
0
        public void GetSitesUserIsMemberOf_NoMemberOfGroups_ReturnsEmptySiteIds()
        {
            var userId = 6;
            var groupName = "notagroup";
            var expectedSiteId = new List<int>();

            
            var cache = GetGroupsCache(_mocks);
            
            
            

            var creator = _mocks.DynamicMock<IDnaDataReaderCreator>();
            var diag = _mocks.DynamicMock<IDnaDiagnostics>();
            _mocks.ReplayAll();

            var obj = new UserGroups(creator, diag, cache, null, null);

            var siteIds = obj.GetSitesUserIsMemberOf(userId, groupName);
            Assert.AreEqual(expectedSiteId.Count, siteIds.Count);

        }
Exemplo n.º 55
0
        public void GetSitesUserIsMemberOf_ValidUserWithGroups_ReturnsCorrectSiteIds()
        {
            var userId = 7;
            var siteId = 2;

            var groupName = "editor";
            var siteIds = new Queue<int>();
            siteIds.Enqueue(1);
            siteIds.Enqueue(2);
            siteIds.Enqueue(2);
            var userIds = new Queue<int>();
            userIds.Enqueue(6);
            userIds.Enqueue(6);
            userIds.Enqueue(7);
            
            var cache = GetGroupsCache(_mocks);

            var readerMembers = _mocks.DynamicMock<IDnaDataReader>();
            readerMembers.Stub(x => x.Read()).Return(true).Repeat.Times(3);
            readerMembers.Stub(x => x.GetString("name")).Return(groupName);
            readerMembers.Stub(x => x.GetInt32("siteid")).Return(1).WhenCalled(x => x.ReturnValue = siteIds.Dequeue());
            readerMembers.Stub(x => x.GetInt32("userid")).Return(1).WhenCalled(x => x.ReturnValue = userIds.Dequeue());
            readerMembers.Stub(x => x.GetInt32("groupid")).Return(1);

            var readerGetAllGroups = _mocks.DynamicMock<IDnaDataReader>();
            readerGetAllGroups.Stub(x => x.Read()).Return(true).Repeat.Once();
            readerGetAllGroups.Stub(x => x.GetString("groupname")).Return(groupName);
            readerGetAllGroups.Stub(x => x.GetInt32("groupid")).Return(1);

            var readerGetUserGroups = _mocks.DynamicMock<IDnaDataReader>();
            readerGetUserGroups.Stub(x => x.Read()).Return(false);

            var creator = _mocks.DynamicMock<IDnaDataReaderCreator>();
            creator.Stub(x => x.CreateDnaDataReader("GetAllGroups")).Return(readerGetAllGroups);
            creator.Stub(x => x.CreateDnaDataReader("fetchgroupsforuser")).Return(readerMembers);

            var diag = _mocks.DynamicMock<IDnaDiagnostics>();
            _mocks.ReplayAll();

            var obj = new UserGroups(creator, diag, cache, null, null);

            var returnedSiteIds = obj.GetSitesUserIsMemberOf(userId, groupName);
            Assert.AreEqual(1, returnedSiteIds.Count);
            Assert.IsTrue(returnedSiteIds.Contains(siteId));
        
        }
Exemplo n.º 56
0
        public void SendSignal_WithUserId_SendsCorrectSignal()
        {
            var url = "1.0.0.1";
            var userId = 1;
            
            var cache = GetGroupsCache(_mocks);
            
            
            

            var creator = _mocks.DynamicMock<IDnaDataReaderCreator>();
            var diag = _mocks.DynamicMock<IDnaDiagnostics>();
            List<string> servers = new List<string>() { url };
            _mocks.ReplayAll();

            var obj = new UserGroups(creator, diag, cache, servers, servers);

            var groupsList = obj.GetUsersGroupsForSite(int.MaxValue, int.MaxValue);
            Assert.IsNotNull(groupsList);
            Assert.AreEqual(0, groupsList.Count);
            obj.SendSignal(userId);
            diag.AssertWasCalled(x => x.WriteToLog("SendingSignal", string.Format("http://{0}/dna/moderation/signal?action={1}&userid={2}", url, obj.SignalKey, userId)));
            diag.AssertWasCalled(x => x.WriteToLog("SendingSignal", string.Format("http://{0}/dna/moderation/dnasignal?action={1}&userid={2}", url, obj.SignalKey, userId)));

        }
Exemplo n.º 57
0
        public void SendSignal_MultipleServersWithUserId_SendsCorrectSignal()
        {
            var url = "1.0.0.1";
            var userId = 1;
            var cache = GetGroupsCache(_mocks);

            var creator = _mocks.DynamicMock<IDnaDataReaderCreator>();
            var diag = _mocks.DynamicMock<IDnaDiagnostics>();
            List<string> servers = new List<string>() { url, url };
            _mocks.ReplayAll();

            var obj = new UserGroups(creator, diag, cache, servers, servers);

            obj.SendSignal(userId);
            diag.AssertWasCalled(x => x.WriteToLog("SendingSignal", string.Format("http://{0}/dna/moderation/signal?action={1}&userid={2}", url, obj.SignalKey, userId)));
            diag.AssertWasCalled(x => x.WriteToLog("SendingSignal", string.Format("http://{0}/dna/moderation/dnasignal?action={1}&userid={2}", url, obj.SignalKey, userId)));
        }
Exemplo n.º 58
0
        public void InitialiseAllUsersAndGroups_ExceptionThrown_ThrowsException()
        {
            var groupName = "editor";
            

            var cache = _mocks.DynamicMock<ICacheManager>();
            cache.Stub(x => x.Contains("")).Constraints(Is.Anything()).Return(false);

            var readerMembers = _mocks.DynamicMock<IDnaDataReader>();
            readerMembers.Stub(x => x.Execute()).Throw(new Exception("fetchgroupsandmembersbysite"));


            var readerGetAllGroups = _mocks.DynamicMock<IDnaDataReader>();
            readerGetAllGroups.Stub(x => x.Read()).Return(true).Repeat.Once();
            readerGetAllGroups.Stub(x => x.GetString("groupname")).Return(groupName);

            var creator = _mocks.DynamicMock<IDnaDataReaderCreator>();
            creator.Stub(x => x.CreateDnaDataReader("fetchgroupsandmembersbysite")).Return(readerMembers);
            creator.Stub(x => x.CreateDnaDataReader("GetAllGroups")).Return(readerGetAllGroups);


            var diag = _mocks.DynamicMock<IDnaDiagnostics>();
            _mocks.ReplayAll();

            bool exceptionThrown = false;
            try
            {
                var obj = new UserGroups(creator, diag, cache, null, null);
            }
            catch (Exception e)
            {
                Assert.AreEqual("fetchgroupsandmembersbysite", e.Message);
                exceptionThrown = true;
            }
            Assert.IsTrue(exceptionThrown);
            readerGetAllGroups.AssertWasNotCalled(x => x.Execute());

        }
Exemplo n.º 59
0
		/// <summary>
		/// Designed to be called once at application Start-up
		/// </summary>
		/// <param name="rootPath">The folder that's the root of the application</param>
		public static void OnDnaStartup(string rootPath)
		{
#if DEBUG
            /**************************************
             *                                    *
             *    DEBUGGING FROM THE WORD GO!     *
             *                                    *
             **************************************/
            // System.Diagnostics.Debugger.Launch();
#endif

			_appContext = new AppContext(rootPath);

            _dnaCacheManager = CacheFactory.GetCacheManager();
		    

			DnaDiagnostics.Initialise(TheAppContext.Config.InputLogFilePath, "DNALOG");
#if DEBUG
			DnaDiagnostics.WriteHeader("OnDnaStartup - DEBUG");
#else
                DnaDiagnostics.WriteHeader("OnDnaStartup - RELEASE");
#endif

			Statistics.InitialiseIfEmpty(/*TheAppContext*/);

            //load the smiley list
            SmileyTranslator.LoadSmileys(ReaderCreator);

            ICacheManager cacheMemcachedManager = null;
            try
            {
                cacheMemcachedManager = CacheFactory.GetCacheManager("Memcached");
            }
            catch (Exception error)
            {
                DnaDiagnostics.Default.WriteWarningToLog("OnDnaStartup", "Unable to use memcached cachemanager - falling back to static inmemory");
                DnaDiagnostics.Default.WriteExceptionToLog(error);
                cacheMemcachedManager = new StaticCacheManager();
            }

            //new signal objects below here
            _appContext.TheSiteList = new SiteList(AppContext.ReaderCreator, DnaDiagnostics.Default, cacheMemcachedManager, TheAppContext._dnaConfig.RipleyServerAddresses, TheAppContext._dnaConfig.DotNetServerAddresses);
            var bannedEmails = new BannedEmails(AppContext.ReaderCreator, DnaDiagnostics.Default, cacheMemcachedManager, TheAppContext._dnaConfig.RipleyServerAddresses, TheAppContext._dnaConfig.DotNetServerAddresses);
            var userGroups = new UserGroups(AppContext.ReaderCreator, DnaDiagnostics.Default, cacheMemcachedManager, TheAppContext._dnaConfig.RipleyServerAddresses, TheAppContext._dnaConfig.DotNetServerAddresses);
            var profanityFilter = new ProfanityFilter(AppContext.ReaderCreator, DnaDiagnostics.Default, cacheMemcachedManager, TheAppContext._dnaConfig.RipleyServerAddresses, TheAppContext._dnaConfig.DotNetServerAddresses);
            var moderationClasses = new ModerationClassListCache(AppContext.ReaderCreator, DnaDiagnostics.Default, cacheMemcachedManager, TheAppContext._dnaConfig.RipleyServerAddresses, TheAppContext._dnaConfig.DotNetServerAddresses);

            // Setup the banned user agents list
            InitialiseBannedUserAgents();
		}
Exemplo n.º 60
0
        public void GetUserGroupsStats_GetsValidStats_ReturnsValidObject()
        {
            
            var cache = GetGroupsCache(_mocks);
            
            var creator = _mocks.DynamicMock<IDnaDataReaderCreator>();
            var diag = _mocks.DynamicMock<IDnaDiagnostics>();
            _mocks.ReplayAll();

            var obj = new UserGroups(creator, diag, cache, null, null);


            var stats = obj.GetStats(typeof(UserGroups));
            Assert.IsNotNull(stats);
            Assert.AreEqual(typeof(UserGroups).AssemblyQualifiedName, stats.Name);
            Assert.AreEqual(obj.InternalObjects.Count.ToString(), stats.Values["NumberOfAllUsersGroupsAndSites"]);
            Assert.AreEqual(((List<UserGroup>)obj.InternalObjects[UserGroups.GetCacheKey(UserGroups.ALLGROUPSKEY)]).Count.ToString(), stats.Values["NumberOfGroups"]);

        }