Exemplo n.º 1
0
        private static User CreateAndSaveTestUser(IDocumentStore store, string userId,int points)
        {
            var subjectUser = new User { Id = userId, FirstName = "blah", LastName = "blah" ,RewardPointsLeft = points};

            using (var session = store.OpenSession())
            {
                session.Store(subjectUser);
                session.SaveChanges();
            }
            return subjectUser;
        }
Exemplo n.º 2
0
        public virtual void init()
        {
            Orguser = new User { Id = IlluminateDatabase.GenerateId<User>(), NameIdentifier = "nameidentifier", OrgKey = "OrgKey", EmailAddress = "*****@*****.**", DateOfBirth = new DateTime(1990, 1, 1), FirstName = "Test", LastName = "User", Config = new Config { Settings = new Dictionary<string, object>() } };
            Manager = new User { Id = IlluminateDatabase.GenerateId<User>(), NameIdentifier = "managernameidentifier", OrgKey = "OrgKey", EmailAddress = "*****@*****.**", DateOfBirth = new DateTime(1991, 1, 1), FirstName = "Test", LastName = "Manager", Config = new Config { Settings = new Dictionary<string, object>() } };
            //set as manager
            Manager.Roles.Add(Role.GetRole(Role.BuiltInRole.Manager));

            Orguser.AddManager(Manager); 



        }
Exemplo n.º 3
0
        private void CreateTestUsers(IDocumentStore store)
       {
           
           using (var session = store.OpenSession())
           {
                _user1 = new User {Id = TestToID1,CreatedDate = DateTime.Today.AddDays(0-2)};
               session.Store(_user1);

                _user2 = new User { Id = TestToID2 };
               session.Store(_user2);
               session.SaveChanges();
           }
       }
Exemplo n.º 4
0
        public void TestOverdueTasks()
        {
            InitOrgStore();
            IndexOrgStore();
            var assignedUser = new User { Id = IlluminateDatabase.GenerateId<User>(), NameIdentifier = "nameidentifier", OrgKey = "OrgKey", EmailAddress = "*****@*****.**", DateOfBirth = new DateTime(1990, 1, 1), FirstName = "Test", LastName = "User", Config = new Config { Settings = new Dictionary<string, object>() } };
            var newtask = new Task
            {
                Id = IlluminateDatabase.GenerateId<Task>(),
                Type = new TaskType { Name = "test task" },
                DueDate = DateTime.Now.AddDays(-1),
                ConsolidatedCompletionDate = DateTime.Now,
                CreatedBy = Orguser.ToSimpleUser(),
                Title = "test task title",
                Description = "test task description",
                AssignedUsers = new List<SimpleUser> { assignedUser .ToSimpleUser()}
            };
            //store the task in the db
            using (var session = OrgStore.OpenSession())
            {
                session.Store(assignedUser);
                session.Store(newtask);
                
                
                session.SaveChanges();
                newtask.UpdateAssignees(session);
                while (OrgStore.DatabaseCommands.GetStatistics().StaleIndexes.Length != 0)
                {
                    Thread.Sleep(100);
                }

                var result = Task.GetNumberOverdueContextTasks(assignedUser.Id, null, session);
                Assert.AreEqual(1,result);

                //pretend user completes task

                newtask.CompletedDate = DateTime.Now;
                newtask.ConsolidatedCompletionDate = DateTime.Now;
                session.SaveChanges();
                while (OrgStore.DatabaseCommands.GetStatistics().StaleIndexes.Length != 0)
                {
                    Thread.Sleep(100);
                }

                result = Task.GetNumberOverdueContextTasks(assignedUser.Id, null, session);
                Assert.AreEqual(0, result);
            }

        }
Exemplo n.º 5
0
        /// <summary>
        /// Get AuthUserViewmodel from given AuthUser and User
        /// </summary>
        /// <param name="au">AuthUser object</param>
        /// <param name="ou">Corresponding OrgUser object</param>
        /// <returns></returns>
        public static AuthUserViewModel FromUser(AuthUser au, User ou)
        {
            
            if(!au.Id.Equals(ou.Id))
                   throw new ArgumentException("AuthUser and User have different Ids");

            return new AuthUserViewModel
                       {
                           Id = au.Id, 
                           ActivationCode = au.ActivationCode, 
                           DateOfBirth = ou.DateOfBirth, 
                           EmailAddress = ou.EmailAddress, 
                           FirstName = ou.FirstName,
                           LastName = ou.LastName, 
                           NameIdentifier = au.NameIdentifier,
                           OrgKey = au.OrgKey,
                           PersonnelNumber = ou.PersonnelNumber,
                           Position = ou.Position,
                       };
        }
Exemplo n.º 6
0
        /// <summary>
        /// Becuse you cant add a managee to a user who cannot manage we cannot allow set acess to the Managees
        /// property directly - so this method allows callers to do it in a safe manner
        /// </summary>
        /// <param name="manager">The manager to add</param>
        /// <param name="relationship">The relationship of the manager to the user. Defaults to "Manager"</param>
        /// <returns>True if the related user has been sucessfully added</returns>
        public bool AddManager(User manager, string relationship = "LineManager")
        {
            if (manager == null)
                throw new ArgumentException("Manager argument cannot be null");

            if (!manager.CanManageOthers)
            {
               
                throw new ArgumentException("The proposed manager does not have the Manager role");
            }
            AddRelationship(manager, relationship);
            return true;
        }
        private void GenerateUsers()
        {
            if(_numUsers>_firstNames.Length)
                throw new ArgumentException(string.Format("Can only create up to {0} users",_firstNames.Length));
            var users = new List<IUser>(_numUsers);
            var rand = new Random();
            for (var count = 0; count < _numUsers; count++)
            {
                var user = new User
                {
                    FirstName = _firstNames[count],
                    LastName = _lastNames[count],
                    CreatedDate = DateTime.Now,
                    DateOfBirth = DateTime.Now.AddYears(GetAge()),
                    EmailAddress = GetEmail(_firstNames[count],_lastNames[count]),
                    Id = IlluminateDatabase.GenerateId<User>(),
                    OrgKey = _orgKey,
                    PersonnelNumber = _rand.Next(1000,10000).ToString(),
                    MobilePhoneNumber = "44756783568",
                    Roles =
                        new List<Role>
                                           {
                                               Role.GetRole(Role.BuiltInRole.Manager),
                                           },
                    Position = _positions[count],
                    
                    Avatar = new Avatar{PublicID = _avatarImages[count],Tags = new []{_orgKey}},


                };
                user.LatestHig= new HIGEntry
                {
                    CaptureDate = DateTime.Now,
                    ConsolidatedCompletionDate = DateTime.Now,
                    Subject = user.ToSimpleUser(),
                    Value =  rand.Next(-2,2),
                    Id = IlluminateDatabase.GenerateId<HIGEntry>(),
                    LastInDay = true
                };
                users.Add(user);
            }

            var ownerUser = new User
            {
                FirstName = _ownerFirstName,
                LastName = _ownerLastName,
                CreatedDate = DateTime.Now,
                DateOfBirth = DateTime.Now.AddYears(GetAge()),
                EmailAddress = _ownerEmail,
                Id = IlluminateDatabase.GenerateId<User>(),
                OrgKey = _orgKey,
                PersonnelNumber = _rand.Next(1000, 10000).ToString(),
                MobilePhoneNumber = "44756783568",
                Roles =
                    new List<Role>
                                           {
                                               Role.GetRole(Role.BuiltInRole.Manager),
                                               Role.GetRole(Role.BuiltInRole.Administrator),
                                               Role.GetRole(Role.BuiltInRole.Analytics),
                                           },
                Position = "Owner",
                RewardPointsLeft = 100000

            };
            foreach (var user in users)
            {
                user.AddManager(ownerUser);
            }
            users.Add(ownerUser);
            _users = users;
            var authUsers = new List<IAuthUser> {ownerUser.ToAuthUser()};
            _authUsers = authUsers;
        }
        public virtual void EmailActivation(AuthUser au, User ou, IDocumentStore orgStore)
        {

            //check not already activated. Work this out from 
            if (String.IsNullOrEmpty(au.ActivationCode))
            {
                throw new Exception("User is already activated");
            }

            var activationurl = String.Format("{0}://{1}/{2}", Request.Url.Scheme, ConfigurationManager.AppSettings["ActivationUrl"], au.ActivationCode);

            var notification = new Notification
                                   {
                                       Title = "New Administrator account for Illuminate",
                                       Body = Email.GetActivationEmailBody(ou, activationurl,au.ActivationCode,""),
                                       Id = IlluminateDatabase.GenerateId<Notification>(),
                                       NotificationRecipients = new[]
                                                                    {
                                                                        new NotificationRecipient
                                                                            {
                                                                                Users = new[] {ou.ToSimpleUser()},
                                                                                NotificationDeliveryTypes =
                                                                                    NotificationDeliveryTypes.Email
                                                                            }
                                                                    },
                                       SendDate = DateTime.Now
                                   };

            using (var session = orgStore.OpenSession())
            {
                session.Store(notification);
                session.SaveChanges();
            }
            
        }
Exemplo n.º 9
0
 public List<Sickness> GetTestSicknesses(User user, int number)
 {
     var Sicknesses = new List<Sickness>();
     for (int i = 1; i <= number; i++)
     {
         var date = DateTime.Now.AddMonths(0 - i);
         var Sickness = new Sickness();
         string SicknessNumber = i.ToString();
         Sickness.Id = IlluminateDatabase.GenerateId<Sickness>();
         Sickness.Subject = new SimpleUser();
         Sickness.Subject.UserId = user.Id;
         Sickness.Subject.FullName = user.FirstName + " " + user.LastName;
         Sickness.StartOfProcess = date;
         Sickness.EndOfProcess = date.AddDays(1);
         Sicknesses.Add(Sickness);
     }
     return Sicknesses;
 }
Exemplo n.º 10
0
 // kpi helper gets date of concern, user, concernid, title- think we only need id, user and event date- need a range of dates, to test
 public List<Concern> GetTestConcerns(User user, int number)
 {
     var Concerns = new List<Concern>();
     var today = DateTime.Now.Date;// by default each concern is today- move month back by 1
     for (int i = 1; i <= number; i++)
     {
         var date = DateTime.Now.AddMonths(0 - i);
         var Concern = new Concern();
         string ConcernNumber = i.ToString();
         Concern.Id = IlluminateDatabase.GenerateId<Concern>();
         Concern.EventDate = date;
         Concern.SubjectUser = new SimpleUser();
         Concern.SubjectUser.UserId = user.Id;
         Concern.SubjectUser.FullName = user.FirstName + " " + user.LastName;
         Concerns.Add(Concern);
     }
     return Concerns;
 }
Exemplo n.º 11
0
 /// <summary>
 /// Is a user a Line Manager of a user = i.e. in their team. 
 /// </summary>
 /// <param name="manager"></param>
 /// <returns></returns>
 public bool InTeamOf(User manager)
 {
     return InTeamOf(manager.Id); 
 }
Exemplo n.º 12
0
        private RedirectResult RedirectToPerson(User user, string id = "")
        {

            //are they in my team?
            if (user.InTeamOf(OrgUser))
            {
                //go to team page
                return RedirectToTeamMember(user.Id, id);
            }
            if (user.Relationships.Any(r => r.UserId == OrgUser.Id))
            {
                //go to user page
                return RedirectToPerson(user.Id, id);
            }
            //TODO: if neither of these, but has admin Role, need to go to Admin page. 
            if (OrgUser.HasRole(Role.GetRole(Role.BuiltInRole.Administrator)))
            {
                //go to user page
                return new RedirectResult("/Administration"); //needs to have userid information sent somehow
            }

            //if get to here, then can't see this user?
            throw new IlluminateException("You cannot access information for this person");
        }
Exemplo n.º 13
0
 /// <summary>
 /// Add a related user to the user. 
 /// </summary>
 /// <param name="relatedUser"></param>
 /// <param name="relationship"></param>
 /// <returns></returns>
 public bool AddRelationship(User relatedUser, string relationship)
 {
     Relationships.Add(relatedUser.ToRelatedUser(relationship));
     return true;
 }
        public void EditAccounts()
        {
            const string userId = "blah";
            var controller = GetAuthenticatedControllerMock<AdministrationController>(Orguser);

            controller.ControllerContext = new ControllerContext(GetContext(false), new RouteData(), controller);
            using (var session = OrgStore.OpenSession())
            {
                var user = new User
                               {
                                   Id = userId,
                                   FirstName = "Billy",
                                   LastName = "Bunter",
                                   EmailAddress = "sasas"
                               };
                session.Store(user);
                session.SaveChanges();
            }
            var account = new Account
            {
                Name = "Bob Baker",
                EmailAddress = "wwewe",
                Id = userId
            };
            var result = controller.EditAccounts(new[] { account });
            var jsonresponse = ValidateAndUnwrapJsonResult(result);

            var data = jsonresponse.Data as AccountsAdminViewModel;
            Assert.IsNull(data.ErrorMessage);
            Assert.IsNotNull(data.SuccessMessage);
            using (var session = OrgStore.OpenSession())
            {
                var changedUser = session.Load<User>(userId);
                Assert.IsNotNull(changedUser);
                Assert.AreEqual(account.EmailAddress, changedUser.EmailAddress);
                Assert.AreEqual(account.Name, changedUser.Name);
            }
        }
        private IEnumerable<User> GetAndSaveTestUsers(int num, IDocumentStore store)
        {
            var users = new List<User>(num);
            using (var session = store.OpenSession())
            {
                for (var count = 1; count <= num; count++)
                {
                    var user = new User
                               {
                                   FirstName = string.Format("firstname{0}", count),
                                   LastName = string.Format("lastname{0}", count),
                                   Id = string.Format("id{0}", count),
                               };
                
                    users.Add(user);
                    session.Store(user);
                }
                session.SaveChanges();
            }
            

            return users;
        }
        public void ManagersForEmployeeNoManagers()
        {
            const string testEmployeeid = "testemployee";
            var testUser = new User()
            {
                Id = testEmployeeid,
                CreatedDate = DateTime.Now
            };
            

           
            using (var session = OrgStore.OpenSession())
            {
                session.Store(testUser);
                
                session.SaveChanges();
            }
            //ARRANGE
            var controller = GetAuthenticatedControllerMock<AdministrationController>(Orguser);

            //set controller context. 
            controller.ControllerContext = new ControllerContext(GetContext(false), new RouteData(), controller);


            var request = new Request
            {
                filter = new FilterLogic
                {
                    filters = new[]
                                                                 {
                                                                     new Filter { Value = testEmployeeid }
                                                                 }
                },
                page = 0,
                skip = 0,
                take = 10

            };
            var result = controller.ManagersForEmployee(request);
            var jsonresponse = ValidateAndUnwrapJsonResult(result);

            var data = jsonresponse.Data as AccountsManagersAdminViewModel;

            Assert.IsNull(jsonresponse.ErrorMessage);
            Assert.AreEqual(data.Count, testUser.Relationships.Count);
            
        }
        public void ManagersForEmployee()
        {
            const string testEmployeeid = "testemployee";
            var testUser = new User()
            {
                Id = testEmployeeid,
                CreatedDate = DateTime.Now
            };
            const string manager1Id = "manager1";
            var manager1 = new User()
            {
                Id = manager1Id,
                CreatedDate = DateTime.Now,
                FirstName = "Bill",
                LastName = "Bunter"
            };
            const string manager2Id = "manager2";
            var manager2= new User()
            {
                Id = manager2Id,
                CreatedDate = DateTime.Now,
                FirstName = "Bob",
                LastName = "Bonter"
            };
           
            manager1.Roles.Add(Role.GetRole( Role.BuiltInRole.Manager));
            manager2.Roles.Add(Role.GetRole(Role.BuiltInRole.Manager));
            testUser.AddManager(manager1);
            testUser.AddManager(manager2);
            using (var session = OrgStore.OpenSession())
            {
                session.Store(testUser);
                session.Store(manager1);
                session.Store(manager2);
                session.SaveChanges();
            }
            //ARRANGE
            var controller = GetAuthenticatedControllerMock<AdministrationController>(Orguser);

            //set controller context. 
            controller.ControllerContext = new ControllerContext(GetContext(false), new RouteData(), controller);

           
            var request = new Request
                              {
                                  filter = new FilterLogic
                                               {
                                                   filters = new []
                                                                 {
                                                                     new Filter { Value = testEmployeeid }
                                                                 }
                                               },
                                               page = 0,
                                               skip = 0,
                                               take = 10

                              };
            var result = controller.ManagersForEmployee(request);
            var jsonresponse = ValidateAndUnwrapJsonResult(result);

            var data = jsonresponse.Data as AccountsManagersAdminViewModel;
            
            Assert.IsNull(jsonresponse.ErrorMessage);
            Assert.AreEqual(data.Count,testUser.Relationships.Count);
            Assert.AreEqual(data.Managers.First().EmployeeId,testUser.Id);
            Assert.AreEqual(data.Managers.First().ManagerEmployeeId, manager1Id);
            Assert.AreEqual(data.Managers.First().ManagerName, manager1.Name);
            Assert.AreEqual(data.Managers.Last().EmployeeId, testUser.Id);
            Assert.AreEqual(data.Managers.Last().ManagerName, manager2.Name);
            Assert.AreEqual(data.Managers.Last().ManagerEmployeeId, manager2Id);
        }
        public ActionResult Create(CreateOrganisationViewModel covm)
        {
            ViewBag.Modules = Modules; 
            ModelState.Remove("Id");
            if (ModelState.IsValid)
            {
                DocumentStore ds; 
                

                //check orgkey is ok. 
                if (MvcApplication.DataBase.GetOrgStore(covm.OrgKey)!=null)
                {
                    throw new Exception(String.Format("Organisation key {0} already exists", covm.OrgKey));
                }

                var org = Mapper.Map<OrganisationViewModel, Organisation>(covm);
                org.OrgKey = org.OrgKey.ToLower();
                
                AuthUser authuser;
                IDocumentStore newOrgStore;
                //create new org record in master store
                using (var session = MasterStore.OpenSession())
                {
                    org.CreatedOn = DateTime.Now;
                    org.IsLive = true;
                    session.Store(org);
                    session.SaveChanges();
                    newOrgStore =CreateOrgDatabase(org,session);

                    //create administrator and email
                    authuser = new AuthUser
                    {
                        ActivationCode = Guid.NewGuid().ToString(),
                        Id = IlluminateDatabase.GenerateId<User>(),
                        OrgKey = org.OrgKey
                    };
                    session.Store(authuser);
                    session.SaveChanges();

                }
                
                var orgUser = new User
                                {
                                    CreatedDate = DateTime.Now,
                                    EmailAddress = covm.AdministratorEmail,
                                    Id = authuser.Id,
                                    FirstName = covm.AdministratorName.Split(' ')[0],
                                    LastName = covm.AdministratorName.Split(' ')[1],
                                    Roles = { Role.GetRole(Role.BuiltInRole.Administrator), Role.GetRole(Role.BuiltInRole.Manager), Role.GetRole(Role.BuiltInRole.Analytics) },
                                    OrgKey = org.OrgKey
                                };
                using (var orgSession = newOrgStore.OpenSession())
                {
                    orgSession.Store(orgUser);
                    orgSession.SaveChanges();
                }
                ProvisionNewDatabase(newOrgStore);
                EmailActivation(authuser, orgUser,newOrgStore);
                
                covm = Mapper.Map<Organisation, CreateOrganisationViewModel>(org); 
            }


            return View("Edit", covm);
        }
Exemplo n.º 19
0
 /// <summary>
 /// Check whether a user is a manager of this user
 /// </summary>
 /// <param name="manager">The user object of the potential manager</param>
 /// <returns>boolean indicator of whether the user can manage this user</returns>
 public bool CanBeManagedBy(User manager)
 {
     return CanBeManagedBy(manager.Id); 
 }
Exemplo n.º 20
0
        public static ExtractedUserData ExtractUserData(string orgKey, string fileData, ref List<string> errorlines, int ignoreLines = 0)
        {
            var sr = new StringReader(fileData);
            string line;
            //ignore first line(s). 
            for (var i = 0; i < ignoreLines; i++)
            {
                sr.ReadLine();
            }

            //parse each line
            var re =
                new Regex(
                    @"^(?<personnelnumber>[^\t]+)\t(?<firstname>[^\t]+)\t(?<lastname>[^\t]+)\t(?<position>[^\t]+)\t(?<email>[^\t]*)\t(?<managers>[^\t]*)$");

            var orgusers = new Dictionary<string, User>();
            var authusers = new Dictionary<string, AuthUser>();
            var managers = new Dictionary<string, string>();

            while ((line = sr.ReadLine()) != null)
            {
                var match = re.Match(line);
                if (match.Success)
                {
                    //create new users. 
                    var au = new AuthUser
                                 {
                                     ActivationCode = Guid.NewGuid().ToString(),
                                     Id = IlluminateDatabase.GenerateId<AuthUser>(),
                                     OrgKey = orgKey
                                 };
                    var ou = new User
                                 {
                                     Id = au.Id,
                                     OrgKey = au.OrgKey,
                                     EmailAddress = match.Groups["email"].Captures[0].Value,
                                     PersonnelNumber = match.Groups["personnelnumber"].Captures[0].Value,
                                     FirstName = match.Groups["firstname"].Captures[0].Value,
                                     LastName = match.Groups["lastname"].Captures[0].Value,
                                     Position = match.Groups["position"].Captures[0].Value,

                                 };


                    managers.Add(ou.PersonnelNumber, match.Groups["managers"].Captures[0].Value);
                    authusers.Add(ou.PersonnelNumber, au);
                    orgusers.Add(ou.PersonnelNumber, ou);
                }
                else
                {
                    errorlines.Add(line);
                }
            }

            //who can manage others? 
            foreach (var a in managers)
            {
                var mlist = a.Value.Replace("\"", String.Empty).Replace(" ", String.Empty).Split(',');
                    //remove " and split on ,
                foreach (var m in mlist)
                {

                    if (!String.IsNullOrWhiteSpace(m) && orgusers.ContainsKey(m)) //check manager exists in import. 
                    {
                        var manager = orgusers[m];
                        var user = orgusers[a.Key];

                        //set manager as manager
                        manager.Roles.Add(Role.GetRole(Role.BuiltInRole.Manager));
                        //add to user's managers. 
                        user.AddManager(manager);
                    }
                }
            }


            var ret = new ExtractedUserData {Authusers = authusers, Orgusers = orgusers};

            return ret; 

        }
        private static IEnumerable<IUser> CreateTestUsers()
        {
            var andy = new User
                           {
                               FirstName = "Andy",
                               CreatedDate = DateTime.Now,
                               DateOfBirth = DateTime.Now.AddYears(-40),
                               EmailAddress = "*****@*****.**",
                               Id = IlluminateDatabase.GenerateId<User>(),
                               OrgKey = OrgName,
                               LastName = "Evans",
                               PersonnelNumber = "1",
                               MobilePhoneNumber = "447539363671",
                               Roles =
                                   new List<Role>
                                       {
                                           Role.GetRole(Role.BuiltInRole.Manager),
                                           Role.GetRole(Role.BuiltInRole.Administrator)
                                       },

                           };
            var mark = new User
                           {
                               FirstName = "Mark",
                               CreatedDate = DateTime.Now,
                               DateOfBirth = DateTime.Now.AddYears(-50),
                               EmailAddress = "*****@*****.**",
                               Id = IlluminateDatabase.GenerateId<User>(),
                               OrgKey = OrgName,
                               LastName = "Renyard",
                               PersonnelNumber = "2",
                               MobilePhoneNumber = "447539502244",
                               Roles =
                                   new List<Role>
                                       {
                                           Role.GetRole(Role.BuiltInRole.Manager),
                                           Role.GetRole(Role.BuiltInRole.Administrator)
                                       }
                           };

            var adrian = new User
                             {
                                 FirstName = "Adrian",
                                 CreatedDate = DateTime.Now,
                                 DateOfBirth = DateTime.Now.AddYears(-40),
                                 EmailAddress = "*****@*****.**",
                                 Id = IlluminateDatabase.GenerateId<User>(),
                                 OrgKey = OrgName,
                                 LastName = "Hall",
                                 PersonnelNumber = "3",
                                 MobilePhoneNumber = "447990597396",
                                 Roles =
                                     new List<Role>
                                         {
                                             Role.GetRole(Role.BuiltInRole.Manager),
                                             Role.GetRole(Role.BuiltInRole.Administrator)
                                         }
                             };
            var carl = new User
                           {
                               FirstName = "Carl",
                               CreatedDate = DateTime.Now,
                               DateOfBirth = DateTime.Now.AddYears(-40),
                               EmailAddress = "*****@*****.**",
                               Id = IlluminateDatabase.GenerateId<User>(),
                               OrgKey = OrgName,
                               LastName = "Davies",
                               PersonnelNumber = "4",
                               MobilePhoneNumber = "447446144932",
                               Roles =
                                   new List<Role>
                                       {
                                           Role.GetRole(Role.BuiltInRole.Manager),
                                           Role.GetRole(Role.BuiltInRole.Administrator)
                                       }
                           };
            carl.AddManager(andy);
            mark.AddManager(andy);
            adrian.AddManager(andy);
            andy.AddManager(mark);

            return new List<User>
                                {
                                    carl,
                                    mark,
                                    andy,
                                    adrian,
                                    
                                };
        }
Exemplo n.º 22
0
 public List<User> CreateTestUsers(int numberofusers, string orgKey)
 {
     // think i need id, orgkey and username. 
     var users = new List<User>();
     for(int i = 0; i < numberofusers; i++)
     {
         var user = new User();
         var userNumber = i.ToString();
         user.Id = userNumber + orgKey;
         user.OrgKey = orgKey;
         user.EmailAddress = userNumber + orgKey + "@" + userNumber + orgKey;
         users.Add(user);
     }
     return users;
 }
        public ActionResult Activate(string id)
        {
            var redirectUrl = "/Login?originalurl=" + Request.RawUrl;
            if(string.IsNullOrEmpty(id))
                GetLogger().Warning("User trying to activate with an empty id passed in");
            else
                GetLogger().Info(string.Format("User trying to activate with id {0}",id));
            if (!Request.IsAuthenticated)
            {
                GetLogger().Warning(string.Format("User trying to activate with id {0} is not authenticating - adding activation id to session & redirecting to {1}", id, redirectUrl));
                var cookie = new HttpCookie(ActivationCode, id) {Expires = DateTime.Now.AddHours(2)};
                Response.Cookies.Add(cookie);
                return new RedirectResult(redirectUrl);
            }
            Response.Cookies.Remove(ActivationCode);
            if (string.IsNullOrEmpty(id))
            {
                if (Request.Cookies[ActivationCode] != null)
                {
                    id = Request.Cookies[ActivationCode].Value;
                    GetLogger().Info(string.Format("Activation code in cookie is {0}",id));
                    
                }
                else
                {
                    GetLogger().Info("no activation code in cookie - it is not available so ask user to enter it manually");
                    return RedirectToAction("Index", "Activation");
                }
                    
            }
            if (string.IsNullOrEmpty(id))
                return RedirectToAction("Index", "Activation");   
            GetLogger().Info(string.Format("activating user with code {0}",id));
            //find AuthUser record and create relevant User record in Organisation. 
            using(var masterSession = MasterStore.OpenSession())
            {
                GetLogger().Information(string.Format("got master session"));
                var authUser = (from u in masterSession.Query<AuthUser>() where u.ActivationCode == id select u).FirstOrDefault();
                if (authUser == null)
                {
                    GetLogger().Warn(string.Format("cannot find auth user with code {0}", id));
                    return RedirectToAction("Index", "Activation"); //must activate. 
                }
                GetLogger().Information(string.Format("found auth user by activation key with ID {0} for org {1}", authUser.Id, authUser.OrgKey));
                var claimsInfo = Thread.CurrentPrincipal.Identity as ClaimsIdentity;
                if (claimsInfo == null)
                {
                    GetLogger().Warning(string.Format("cannot get claims identity for {0}", authUser.Id));
                    return RedirectToAction("Index", "Activation");
                }
                var nameIdClaim = claimsInfo.FindFirst(c => c.Type == ClaimTypes.NameIdentifier);
                if (nameIdClaim == null)
                {
                    GetLogger().Warning(string.Format("cannot get nameidentifier claim for {0}", authUser.Id));
                    return RedirectToAction("Index", "Activation");
                   
                }
                //Update AuthUser record with this nameidentifier?
                authUser.NameIdentifier = nameIdClaim.Value;
                GetLogger().Warning(string.Format("got nameidentifier claim for {0}", authUser.Id));
                //now kill the activation key. 
                authUser.ActivationCode = string.Empty;
                masterSession.SaveChanges();

                //create an OrgUser if doesn't already exists.

                if (string.IsNullOrEmpty(authUser.OrgKey))
                {
                    var message = string.Format("Auth user {0} has a null / empty org key", authUser.Id);
                    GetLogger().Error(message);
                    throw new Exception(message);
                }
                var orgStore = GetOrgStore(authUser.OrgKey);
                if (orgStore == null)
                {
                    var message = string.Format("problem finding org store with org key {0} for user {1}", authUser.OrgKey,authUser.Id);
                    GetLogger().Error(message);
                    throw new Exception(message);
                }
                using (var orgSession = orgStore.OpenSession())
                {
                    var orgUser = orgSession.Load<User>(authUser.Id);

                    if (orgUser == null)
                    {
                        GetLogger()
                            .Warn(string.Format("problem when activating user {0} - cannot find in org store {1}",
                                                authUser.Id, authUser.OrgKey));
                        //no orguser set up? Create OrgUser.

                        orgUser = new User
                        {
                            Id = authUser.Id,
                            NameIdentifier = authUser.NameIdentifier,
                            OrgKey = authUser.OrgKey,
                            FirstName = "unknown",
                            LastName = "unknown",
                            EmailAddress = claimsInfo.FindFirst(c => c.Type == ClaimTypes.Email).Value,
                            Language = "en-gb"
                        };
                        orgSession.Store(orgUser);
                        orgSession.SaveChanges();
                    }
                    else
                    {
                        MvcApplication.ClaimsAuthenticationManager.Authenticate(null, Thread.CurrentPrincipal as ClaimsPrincipal);
                    }
                    GetLogger().Information("User {0} activated", orgUser.Name);
                }
            }

            return RedirectToAction("Index", "Home"); 



        }
Exemplo n.º 24
0
        public static void CreateManager()
        {

            var store = new DocumentStore { ConnectionStringName = "RavenServer" };


            store.Initialize();
            using (var session = store.OpenSession())
            {
                var user = new User
                               {
                                   
                                   
                                   DateOfBirth = DateTime.Now,
                                   FirstName = "Santa",
                                   Id = "0b941572-8329-45c0-9449-cc651ff29461",
                                   LastName = "Claus",
                                   EmailAddress = string.Empty,
                                   Language = string.Empty,
                                   LastLogin = DateTime.Now
                                   
                               };
                    //set as manager
                    user.Roles.Add(Role.GetRole(Role.BuiltInRole.Manager));

                    session.Store(user);
                
                session.SaveChanges();
            }

        }
Exemplo n.º 25
0
 // test users
 public List<User> GetTestUsers(int number)
 {
     var users = new List<User>();
     for (int i = 0; i < number; i++)
     {
         var user = new User();
         string userNumber = i.ToString();
         user.Id = userNumber;
         user.FirstName = "user" + userNumber;
         user.LastName = "user" + userNumber;
         user.OrgKey = "TestKey";
         //user.LatestHig.Value = 0;
         users.Add(user);
     }
     return users;
 }
Exemplo n.º 26
0
        public void DoWork(IlluminateDatabase database,IEmailSender emailSender)
        {
            Logger.Information("EmailDailyTasks started");
            
            

            //we need to get a list of tasks that are Overdue, duetoday or due tomorrow. 
            foreach (var db in database.GetAllOrgStores())
            {
                Currentstore = db; 

                List<User> users;
                using (var session = db.OpenSession())
                {
                    users = session.Query<User>().ToList();
                }

                //get the tasks etc for this user. 
                foreach (var user in users)
                {
                    Currentuser = user; 


                    //set culture
                    Thread.CurrentThread.CurrentCulture = user.Culture;


                    var bodyBuilder = new StringBuilder(); 

                    using (var session = db.OpenSession()) //smaller sessions
                    {
                        var targetuser = user;

                        var tasks =
                            session.Query<Task>()
                                    .Where(
                                        x =>
                                        x.ConsolidatedAssignees.Any(a => a.UserId == targetuser.Id) &&
                                        x.DueDate <= DateTime.Today.AddDays(3) && x.CompletedDate == null);
                            
                        var meetings =
                            session.Query<Meeting>()
                                    .Where(
                                        x =>
                                        x.Invitees.Any(i => i.UserId == targetuser.Id) &&
                                        x.DueDate <= DateTime.Today.AddDays(3) &&
                                        x.DueDate >= DateTime.Today); 

                        var items = new List<TimelineItem>();

                        items.AddRange(tasks.ToList().ToTimelineItems());
                        items.AddRange(meetings.ToList().ToTimelineItems());

                        Logger.Information("{0} items for {1}", items.Count, targetuser.Name);

                        var sectionbuilder = new StringBuilder();

                       
                        if (items.Count > 0)
                        {
                         

                            var overduelines =
                                (from i in items
                                    where i.start.Date < DateTime.Today
                                    orderby i.start ascending
                                 select FormatItem(i));
                            sectionbuilder.AppendLine(SubHeader("Overdue tasks"));
                            
                            if (overduelines.Any())
                            {
                                sectionbuilder.Append(String.Join("\n", overduelines.ToList()));
                            }
                            else
                            {
                                sectionbuilder.AppendLine("No items to show<br/>"); 
                            }

                            sectionbuilder.AppendLine("<br/>"); 

                            var todaylines =
                                (from i in items
                                 where i.start.Date == DateTime.Today
                                 orderby i.start ascending
                                 select FormatItem(i));


                            sectionbuilder.AppendLine(SubHeader("Today's tasks"));
                            
                            if (todaylines.Any())
                            {
                                sectionbuilder.Append(String.Join("\n", todaylines.ToList()));
                            }
                            else
                            {
                                sectionbuilder.AppendLine("No items to show<br/>");
                            }

                            sectionbuilder.AppendLine("<br/>");

                            var futurelines =
                                (from i in items
                                 where i.start.Date > DateTime.Today
                                 orderby i.start ascending
                                 select FormatItem(i));


                            sectionbuilder.AppendLine(SubHeader("Upcoming tasks"));
                            
                            if (futurelines.Any())
                            {
                                sectionbuilder.Append(String.Join("\n", futurelines.ToList()));
                            }
                            else
                            {
                                sectionbuilder.AppendLine("No items to show<br/>");
                            }



                        }
                        




                        //TODO: Add Insights



                        //TODO: Add Messages


                        //render section
                        bodyBuilder.Append(Email.WrapSection(sectionbuilder.ToString()));

                        //clear section builder. 
                        sectionbuilder.Clear();


                        //TODO: Add KPIs



                        if (targetuser.CanManageOthers) //TODO: no point if they don't have any managees. 
                        {
                            //TODO: Add Team KPIs


                            //TODO: Add Team HIG

                        }


                        var stuffToSend = (targetuser.EmailAddress == "*****@*****.**"); 


                        //Done
                        if (stuffToSend)//only send if stuff to send?
                        {
                            var email = new Email();
                            email.To.Add(new EmailRecipient
                                             {
                                                 Name = targetuser.Name,
                                                 Email = targetuser.EmailAddress
                                             });


                            const string headertemplate = "<table style='text-align:left;width:100%;padding:0px; margin-top:0px;' cellpadding='0' cellspacing='0'><tr><td style='width:0px;'>{0}&nbsp;</td><td style='font-family: Helvetica,Arial,sans-serif; line-height: 1.3; text-decoration: none; font-size: 18px; font-weight: bold; color: #FFF; padding: 0'>{1}</td></tr></table>"; 

                            var headername = new StringBuilder();
                            headername.AppendLine(targetuser.Name + "<br/>");
                            headername.AppendLine(String.Format("<div style='font-size:14px;'>{0}</div>", DateTime.Today.ToShortDateString()));

                            var headeravatar = String.Format(AvatarImageString,
                                                             ImageHelper.GetAvatarUrl(user.Avatar.PublicID, 50),
                                                             user.Name); 

                            email.Subject = "Your Illuminate Daily Update";
                            email.Body = Email.WrapBody(HostName, "Illuminate Daily Update", String.Format(headertemplate, headeravatar, headername), bodyBuilder.ToString());

                            emailSender.Send(email);
                            
                        }
                    }

                }
            }
            
        }
Exemplo n.º 27
0
 public List<Praise> GetTestPraises(User user, int number)
 {
     var Praises = new List<Praise>();
     var today = DateTime.Now;// by default each concern is today- move month back by 1
     for (int i = 1; i <= number; i++)
     {
         var date = DateTime.Now.AddMonths(0 - i);
         var Praise = new Praise();
         string SicknessNumber = i.ToString();
         Praise.Id = IlluminateDatabase.GenerateId<Praise>();
         Praise.EventDate = date;
         Praise.SubjectUser = new SimpleUser();
         Praise.SubjectUser.UserId = user.Id;
         Praise.SubjectUser.FullName = user.FirstName + " " + user.LastName;
         Praises.Add(Praise);
     }
     return Praises;
 }
Exemplo n.º 28
0
        public static HIGEntry Capture(IDocumentStore store, User user, HIGCaptureViewModel model)
        {
            using (var orgSession = store.OpenSession())
            {
                var simpleUser = user.ToSimpleUser();
            
                var hv = new HIGEntry
                {
                    CaptureDate = DateTime.Now,
                    ConsolidatedCompletionDate = DateTime.Now,
                    Subject = simpleUser,
                    Value = model.HIGValue,
                    Message = model.HIGMessage,
                    Id = IlluminateDatabase.GenerateId<HIGEntry>(),
                    LastInDay = true
                };

                if (user.LatestHig != null && user.LatestHig.CaptureDate.Date == DateTime.UtcNow.Date) //same day
                {
                    //previous hig should be not latest in day. 
                    var lasthig = orgSession.Load<HIGEntry>(user.LatestHig.Id);
                    lasthig.LastInDay = false; 
                }

                //set users latest hig. 
                user.LatestHig = hv;

                if (hv.Value < 0)
                {
                    //alert! Alert!

                    var notify = new Notification
                    {
                        About = simpleUser,
                        Body =
                            String.Format(
                                "{0} added a new negative HIG on {1}. Perhaps you should investigate",
                                user.Name, hv.CaptureDate),
                        SendDate = DateTime.Now,
                        Title = string.Format("HIG Alert for {0}", user.Name),
                        From = EmailRecipient.GetIlluminateRecipient(),
                        NotificationRecipients = new[]
                                                                          {
                                                                              new NotificationRecipient
                                                                                  {

                                                                                      NotificationDeliveryTypes =
                                                                                          NotificationDeliveryTypes
                                                                                              .Toast |
                                                                                          NotificationDeliveryTypes
                                                                                              .Email |
                                                                                              NotificationDeliveryTypes.Sms
                                                                                              ,
                                                                                      
                                                                                      Users = user.Relationships
                                                                                      .Where(r => r.RelationshipName == Role.BuiltInRole.LineManager.ToString() )

                                                                                  }
                                                                          },
                    };
                    orgSession.Store(notify);
                }


                orgSession.Store(user);
                orgSession.Store(hv);
                orgSession.SaveChanges();

                return hv; 
            }
        }
 private User CreateOrEditUser(Account account, bool isEdit)
 {
     var user = new User();
     if (isEdit)
     {
         using (var orgSession = OrgStore.OpenSession())
         {
             //we are editing a user so first get it from raven
             user = orgSession.Load<User>(account.Id);
             if (user == null)//cant find user in database
             {
                 GetLogger().Error(string.Format("Admin: EditOrCreateAccounts: Cannot find user {0}", account.Id));
                 //errorBuilder.Append("Cannot find user"); - what to do about this?
             }
         }
     }
     else
     {
         user.Id = IlluminateDatabase.GenerateId<User>();
         user.OrgKey = OrgKey;
     }
     return user;
 }
Exemplo n.º 30
0
 // need to create some sicknesses for each user
 public List<Sickness> GetTestSicknesses(User user, int number)
 {
     var Sicknesses = new List<Sickness>();
     for (int i = 1; i <= number; i++)
     {
         var Sickness = new Sickness();
         string SicknessNumber = i.ToString();
         Sickness.Id = user.FirstName + SicknessNumber;
         Sickness.Subject = new SimpleUser();
         Sickness.Subject.UserId = user.Id;
         Sickness.Subject.FullName = user.FirstName +" "+ user.LastName;
         Sicknesses.Add(Sickness);
     }
     return Sicknesses;
 }