private async Task <EmployeeContainer> GetEmployeeOrDefaultAsync(string employeeId, CancellationToken token)
        {
            var query     = new EmployeesQuery().WithId(employeeId);
            var employees = await this.employeesRegistry.SearchAsync(query, token);

            return(employees.SingleOrDefault());
        }
Esempio n. 2
0
        public jsResponse <EmployeesCollection, Employees> EmployeesCollection_LoadAll()
        {
            jsResponse <EmployeesCollection, Employees> response = new jsResponse <EmployeesCollection, Employees>();

            try
            {
                EmployeesQuery q = new EmployeesQuery();
                q.Select(q.EmployeeID, q.FirstName, q.LastName);

                EmployeesCollection collection = new EmployeesCollection();
                collection.Load(q);

                if (collection.Count == 0)
                {
                    EnsureData();

                    collection = new EmployeesCollection();
                    collection.LoadAll();
                }

                response.collection = collection;
            }
            catch (Exception ex)
            {
                response.exception = ex.Message;
            }

            return(response);
        }
Esempio n. 3
0
        public async Task <IActionResult> FilterEmployees(
            [FromQuery] string departmentId,
            [FromQuery] string roomNumber,
            [FromQuery] string name,
            CancellationToken token)
        {
            var query = EmployeesQuery.Create();

            if (!string.IsNullOrWhiteSpace(departmentId))
            {
                query = query.ForDepartment(departmentId);
            }

            if (!string.IsNullOrWhiteSpace(roomNumber))
            {
                query = query.ForRoom(roomNumber);
            }

            if (!string.IsNullOrWhiteSpace(name))
            {
                query = query.WithNameFilter(name);
            }

            var employees = await this.LoadEmployeesAsync(query, token);

            return(this.Ok(employees));
        }
Esempio n. 4
0
        private void RefreshHead(IActorRef requestor)
        {
            var requestors = new List <IActorRef>()
            {
                requestor
            };

            void RefreshingHead(object message)
            {
                switch (message)
                {
                case EmployeesQuery.Response queryResult:
                    this.head = queryResult.Employees.FirstOrDefault();
                    this.RefreshEmployees(requestors);
                    break;

                case RefreshDepartmentInfo newInfo when newInfo.Department.DepartmentId == this.departmentInfo.DepartmentId:
                    requestors.Add(this.Sender);
                    break;

                default:
                    this.Stash.Stash();
                    break;
                }
            }

            this.organizationEmployeesActor.Tell(EmployeesQuery.Create().WithId(this.departmentInfo.ChiefId));
            this.Become(RefreshingHead);
        }
Esempio n. 5
0
 protected override EmployeesQuery GetEmployeesQuery(DateTime date)
 {
     return(EmployeesQuery.Create().WithHireDate(new DateQuery()
     {
         Day = date.Day, Month = date.Month
     }));
 }
Esempio n. 6
0
        public async Task <QueryResult <Employee> > ListAsync(EmployeesQuery query)
        {
            IQueryable <Employee> queryable = _context.Employees
                                              .Include(p => p.Activity)
                                              .AsNoTracking();

            // AsNoTracking tells EF Core it doesn't need to track changes on listed entities. Disabling entity
            // tracking makes the code a little faster
            if (query.ActivityId.HasValue && query.ActivityId > 0)
            {
                queryable = queryable.Where(p => p.ActivityId == query.ActivityId);
            }

            // Here I count all items present in the database for the given query, to return as part of the pagination data.
            int totalItems = await queryable.CountAsync();

            // Here I apply a simple calculation to skip a given number of items, according to the current page and amount of items per page,
            // and them I return only the amount of desired items. The methods "Skip" and "Take" do the trick here.
            List <Employee> employees = await queryable.Skip((query.Page - query.ItemsPerPage) *query.ItemsPerPage)
                                        .Take(query.ItemsPerPage)
                                        .ToListAsync();

            // Finally I return a query result, containing all items and the amount of items in the database (necessary for client calculations of pages).
            return(new QueryResult <Employee>
            {
                Items = employees,
                TotalItems = totalItems,
            });
        }
        private async Task <EmployeeMetadata> GetEmployee(string employeeId)
        {
            var employeesResponse = await this.organizationActor.Ask <EmployeesQuery.Response>(
                EmployeesQuery.Create().WithId(employeeId));

            return(employeesResponse.Employees.FirstOrDefault()?.Metadata);
        }
Esempio n. 8
0
        internal void Test(TestServices services, EmployeesQuery q, Ref <Employee> employee, IReadOnlyCollection <EmployeeRM> result)
        {
            GIVEN["a query"] = () => {
                services = new TestServices(b => b
                                            .Services(c => c.RegisterType <EmployeesQuery>().AsImplementedInterfaces())
                                            .UseDefaults());

                q = new EmployeesQuery(services.GetRequiredService <IEventStore>());

                var e = new Employee(ID.NewID(), "Test employee");
                services.Save(e);
                employee = e;

                EmployeeCodes ec = new EmployeeCodes();
                ec.AssignCode(employee, "1234");
                services.Save(ec);
            };

            WHEN["running the query"] = () => result = q.Run(services.GetRequiredService <IContext>());

            THEN["the result is correct"] = () => result.Should().BeEquivalentTo(new EmployeeRM(employee)
            {
                Code = "1234",
                Name = "Test employee"
            });

            WHEN["running the query via container"] = () => result = services.RunQuery(new GetEmployees()).Result;
            THEN["it returns the result"]           = () => result.Should().NotBeEmpty();
        }
Esempio n. 9
0
        public int Employees_GetCount(string serializedQuery)
        {
            EmployeesQuery query = EmployeesQuery.SerializeHelper.FromXml(
                serializedQuery, typeof(EmployeesQuery), AllKnownTypes) as EmployeesQuery;

            return(query.ExecuteScalar <int>());
        }
Esempio n. 10
0
        public async Task <IReadOnlyCollection <EmployeeContainer> > SearchAsync(EmployeesQuery query, CancellationToken token)
        {
            var organization = this.actorSystem.ActorSelection(this.pathsBuilder.Get(WellKnownActorPaths.Organization));
            var response     = await organization.Ask <EmployeesQuery.Response>(query, this.timeoutSettings.Timeout, token);

            return(response.Employees);
        }
        private UntypedReceive GetUserEmployee()
        {
            void OnMessage(object message)
            {
                switch (message)
                {
                case ReceiveTimeout _:
                    Log.Debug($"Cannot get permissions for '${this.userIdentity}' due to timeout");
                    this.ReplyAndStop();
                    break;

                case EmployeesQuery.Response userEmployee when userEmployee.Employees.Count == 0:
                    Log.Debug($"Cannot find an employee for '{this.userIdentity}'");
                    this.ReplyAndStop();
                    break;

                case EmployeesQuery.Response userEmployee:
                    this.defaultEmployeePermission = ExistingEmployeeDefaultPermission;
                    BulkBumpPermissions(userEmployee.Employees.Select(x => x.Metadata.EmployeeId), SelfPermissions, this.permissionsForEmployees);

                    //that can be fixed (as array, not First(), when DepartmentsQuery starts to
                    //support arrays for Heads and DepartmentIds
                    this.Become(this.GetOwnDepartments(userEmployee.Employees.First().Metadata));
                    break;

                default:
                    this.Unhandled(message);
                    break;
                }
            }

            this.organizationActor.Tell(EmployeesQuery.Create().WithIdentity(this.userIdentity));
            return(OnMessage);
        }
Esempio n. 12
0
        private void RefreshEmployees(List <IActorRef> requestors)
        {
            void RefreshingEmployees(object message)
            {
                switch (message)
                {
                case EmployeesQuery.Response queryResult:
                    this.employees.Clear();
                    this.employees.AddRange(queryResult.Employees);

                    this.Become(this.RefreshFinished(requestors));
                    break;

                case RefreshDepartmentInfo newInfo when newInfo.Department.DepartmentId == this.departmentInfo.DepartmentId:
                    requestors.Add(this.Sender);
                    break;

                default:
                    this.Stash.Stash();
                    break;
                }
            }

            this.organizationEmployeesActor.Tell(EmployeesQuery.Create().ForDepartment(this.departmentInfo.DepartmentId));
            this.Become(RefreshingEmployees);
        }
Esempio n. 13
0
        public EmployeeSearch(IEnumerable <IActorRef> allEmployees, IEnumerable <IActorRef> requesters, EmployeesQuery query)
        {
            this.employeeActorsToReply = new HashSet <IActorRef>(allEmployees);
            this.requesters            = new HashSet <IActorRef>(requesters);
            this.query = query;

            this.Self.Tell(StartSearch);
        }
Esempio n. 14
0
        static private void GetTheCount()
        {
            EmployeesQuery q = new EmployeesQuery();

            q.Select(q.Count());
            q.Where(q.LastName.Like("%a"));

            int count = q.ExecuteScalar <int>();
        }
Esempio n. 15
0
        public EmployeesCollection Employees_LoadByDynamic(string serializedQuery)
        {
            EmployeesQuery query = EmployeesQuery.SerializeHelper.FromXml(
                serializedQuery, typeof(EmployeesQuery), AllKnownTypes) as EmployeesQuery;

            EmployeesCollection coll = new EmployeesCollection();

            coll.es.IsLazyLoadDisabled = true;
            coll.Load(query);
            return(coll);
        }
Esempio n. 16
0
        GetAdditionalData(CalendarEventChanged message)
        {
            var ownerEmployeeTask = this.organizationActor.Ask <EmployeesQuery.Response>(
                EmployeesQuery.Create().WithId(message.NewEvent.EmployeeId));
            var ownerPreferencesTask = this.userPreferencesActor.Ask <GetUserPreferencesMessage.Response>(
                new GetUserPreferencesMessage(message.NewEvent.EmployeeId));

            await Task.WhenAll(ownerEmployeeTask, ownerPreferencesTask);

            return(ownerEmployeeTask.Result, ownerPreferencesTask.Result);
        }
Esempio n. 17
0
        private string GetCacheKeyForEmployeesQuery(EmployeesQuery query)
        {
            string key = CacheKeys.EmployeesList.ToString();

            if (query.ActivityId.HasValue && query.ActivityId > 0)
            {
                key = string.Concat(key, "_", query.ActivityId.Value);
            }

            key = string.Concat(key, "_", query.Page, "_", query.ItemsPerPage);
            return(key);
        }
        public async Task <EmployeeContainer> FindOrDefaultAsync(ClaimsPrincipal user, CancellationToken cancellationToken)
        {
            if (!user.Identity.IsAuthenticated)
            {
                return(null);
            }

            var query     = EmployeesQuery.Create().WithIdentity(user.Identity.Name);
            var employees = await this.employeesRegistry.SearchAsync(query, cancellationToken);

            return(employees.SingleOrDefault());
        }
Esempio n. 19
0
        public async Task <QueryResult <Employee> > ListAsync(EmployeesQuery query)
        {
            // Here I list the query result from cache if they exist, but now the data can vary according to the category ID, page and amount of
            // items per page. I have to compose a cache to avoid returning wrong data.
            string cacheKey = GetCacheKeyForEmployeesQuery(query);

            var employee = await _cache.GetOrCreateAsync(cacheKey, (entry) => {
                entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1);
                return(_employeeRepository.ListAsync(query));
            });

            return(employee);
        }
Esempio n. 20
0
        private void buttonQuery_Click(object sender, EventArgs e)
        {
            EmployeesQuery q = new EmployeesQuery("emp");

            q.Select(q.EmployeeID, q.FirstName, q.LastName, q.HireDate, q.BirthDate);

            q.Where(q.LastName.Like("%" + txtLastName.Text + "%"));
            q.OrderBy(q.LastName.Ascending);

            coll = svc.Employees_QueryForCollection(EmployeesQuery.SerializeHelper.ToXml(q));
            coll.EnableHierarchicalBinding = false;
            _bindingSource.DataSource      = coll;
        }
Esempio n. 21
0
        GetAdditionalData(CalendarEventAssignedToApprover message)
        {
            var ownerEmployeeTask = this.organizationActor.Ask <EmployeesQuery.Response>(
                EmployeesQuery.Create().WithId(message.Event.EmployeeId));
            var approverPreferencesTask = this.userPreferencesActor.Ask <GetUserPreferencesMessage.Response>(
                new GetUserPreferencesMessage(message.ApproverId));
            var approverPushTokensTask = this.pushDevicesActor.Ask <GetDevicePushTokensByEmployee.Success>(
                new GetDevicePushTokensByEmployee(message.ApproverId));

            await Task.WhenAll(ownerEmployeeTask, approverPreferencesTask, approverPushTokensTask);

            return(ownerEmployeeTask.Result, approverPreferencesTask.Result, approverPushTokensTask.Result);
        }
Esempio n. 22
0
        public Form1()
        {
            InitializeComponent();

            this.dataGrid.AutoGenerateColumns = true;

            EmployeesQuery q = new EmployeesQuery();

            q.Select(q.EmployeeID, q.FirstName, q.LastName, q.HireDate, q.BirthDate, (q.LastName + ", " + q.FirstName).As("Fullname"));

            EmployeesCollectionProxyStub proxyColl = svc.Employees_QueryForCollection(EmployeesQuery.SerializeHelper.ToXml(q));

            _bindingSource.DataSource = coll = proxyColl.GetCollection();
        }
        public EmployeesProxyStub Employees_QueryForEntity(string serializedQuery)
        {
            EmployeesQuery query = EmployeesQuery.SerializeHelper.FromXml(
                serializedQuery, typeof(EmployeesQuery), AllKnownTypes) as EmployeesQuery;

            Employees obj = new Employees();

            if (obj.Load(query))
            {
                return(obj);
            }

            return(null);
        }
        public EmployeesCollectionProxyStub Employees_QueryForCollection(string serializedQuery)
        {
            EmployeesQuery query = EmployeesQuery.SerializeHelper.FromXml(
                serializedQuery, typeof(EmployeesQuery), AllKnownTypes) as EmployeesQuery;

            EmployeesCollection coll = new EmployeesCollection();

            if (coll.Load(query))
            {
                return(coll);
            }

            return(null);
        }
        private static bool CheckFilter(EmployeeMetadata employee, EmployeesQuery query)
        {
            if ((query.DepartmentId != null) && (employee.DepartmentId != query.DepartmentId))
            {
                return(false);
            }

            if ((query.EmployeeId != null) && (employee.EmployeeId != query.EmployeeId))
            {
                return(false);
            }

            if ((query.RoomNumber != null) && (employee.RoomNumber != query.RoomNumber))
            {
                return(false);
            }

            if ((query.Sid != null) && !string.Equals(employee.Sid, query.Sid, StringComparison.InvariantCultureIgnoreCase))
            {
                return(false);
            }

            if ((query.Identity != null) && !employee.IdentityAliases.Contains(query.Identity))
            {
                return(false);
            }

            if ((query.NameFilter != null) && !(employee.Name?.IndexOf(query.NameFilter, 0, StringComparison.InvariantCultureIgnoreCase) >= 0))
            {
                return(false);
            }

            if ((query.HireDate != null) && !query.HireDate.Matches(employee.HireDate))
            {
                return(false);
            }

            if ((query.BirthDate != null) && (!employee.BirthDate.HasValue || !query.BirthDate.Matches(employee.BirthDate.Value)))
            {
                return(false);
            }

            if ((query.IsWorking == true && employee.FireDate != null) || (query.IsWorking == false && employee.FireDate == null))
            {
                return(false);
            }

            return(true);
        }
        public Hierarchical()
        {
            InitializeComponent();

            EmployeesQuery q = new EmployeesQuery();

            q.es.Top = 15;
            q.Select(q.EmployeeID, q.FirstName, q.LastName, q.BirthDate.As("ExtraColumn"));

            EmployeesCollection coll = new EmployeesCollection();

            coll.Load(q);

            dataGrid1.DataSource = coll;
        }
Esempio n. 27
0
        private async Task <EmployeeModel[]> LoadEmployeesAsync(EmployeesQuery query, CancellationToken token)
        {
            var allPermissions = await this.permissionsLoader.LoadAsync(this.User);

            var employees = await this.employeesRegistry.SearchAsync(query, token);

            var tasks = employees
                        .Where(x => allPermissions.GetPermissions(x).HasFlag(EmployeePermissionsEntry.ReadEmployeeInfo))
                        .Select(async x =>
            {
                var employee            = EmployeeModel.FromMetadata(x.Metadata);
                var employeePermissions = allPermissions.GetPermissions(x);

                if (!employeePermissions.HasFlag(EmployeePermissionsEntry.ReadEmployeePhone))
                {
                    employee.MobilePhone = null;
                }

                if (employeePermissions.HasFlag(EmployeePermissionsEntry.ReadEmployeeVacationsCounter))
                {
                    var vacationsCredit = await x.Calendar
                                          .VacationsActor
                                          .Ask <GetVacationsCredit.Response>(GetVacationsCredit.Instance, this.timeoutSettings.Timeout, token);
                    employee.VacationDaysLeft = vacationsCredit.VacationsCredit;
                }

                if (employeePermissions.HasFlag(EmployeePermissionsEntry.ReadEmployeeDayoffsCounter))
                {
                    var workhoursCredit = await x.Calendar
                                          .WorkHoursActor
                                          .Ask <GetWorkHoursCredit.Response>(GetWorkHoursCredit.Instance, this.timeoutSettings.Timeout, token);
                    employee.HoursCredit = workhoursCredit.WorkHoursCredit;
                }

                return(employee);
            });

            var employeeModels = await Task.WhenAll(tasks);

            if ((employeeModels.Length == 0) && (query.EmployeeId != null))
            {
                Log.Debug($"Employees search list is empty for {query.EmployeeId}. Registry returned {employees.Count} employees. User {this.User.Identity.Name}");
            }

            this.FillPhotoUrls(employeeModels);

            return(employeeModels);
        }
Esempio n. 28
0
        private void EnsureData()
        {
            EmployeesQuery q = new EmployeesQuery();

            q.tg.CountAll = true;

            int i = q.ExecuteScalar <int>();

            if (i == 0)
            {
                Employees emp = new Employees();
                emp.FirstName = "Mike";
                emp.LastName  = "Griffin";
                emp.Save();
            }
        }
        GetAdditionalData(CalendarEventApprovalsChanged message)
        {
            var lastApproval = message.Approvals
                               .OrderByDescending(a => a.Timestamp)
                               .First();

            var ownerPreferencesTask = this.userPreferencesActor.Ask <GetUserPreferencesMessage.Response>(
                new GetUserPreferencesMessage(message.Event.EmployeeId));
            var ownerPushTokensTask = this.pushDevicesActor.Ask <GetDevicePushTokensByEmployee.Success>(
                new GetDevicePushTokensByEmployee(message.Event.EmployeeId));
            var approverEmployeeTask = this.organizationActor.Ask <EmployeesQuery.Response>(
                EmployeesQuery.Create().WithId(lastApproval.ApprovedBy));

            await Task.WhenAll(ownerPreferencesTask, ownerPushTokensTask, approverEmployeeTask);

            return(ownerPreferencesTask.Result, ownerPushTokensTask.Result, approverEmployeeTask.Result);
        }
Esempio n. 30
0
        private async Task <IEnumerable <object> > GetEmailNotifications(
            string employeeId,
            UserPreferences userPreferences,
            IEnumerable <CalendarEvent> vacations)
        {
            if (!userPreferences.EmailNotifications)
            {
                return(Enumerable.Empty <EmailNotification>());
            }

            var employeeResponse = await this.organizationActor.Ask <EmployeesQuery.Response>(
                EmployeesQuery.Create().WithId(employeeId));

            var employeeMetadata = employeeResponse.Employees.First().Metadata;

            return(vacations.Select(e => this.CreateEmailNotification(e, employeeMetadata)));
        }
Esempio n. 31
0
        public IEnumerable<EmployeeDto> GetEmployees(EmployeesQuery parameters)
        {
            var orderBy = GetOrderByFunc(parameters.SortOrder);
            var filter = GetFilterExpr(
                parameters.MinSalary,
                parameters.MaxSalary,
                parameters.StartDate,
                parameters.EndDate,
                parameters.SearchKeyword);
            var query = unitOfWork.EmployeeRepository.Get(filter, orderBy).AsExpandable();

            var employees = query.ToPagedList(parameters.PageNumber, parameters.PageSize);
            var employeesDto = employees.Select(e => mapper.Map<EmployeeDto>(e));

            return employeesDto;
        }