예제 #1
0
    protected People GetVicesAndAdmins()
    {
        People result = new People();


        foreach (BasicPersonRole role in _authority.LocalPersonRoles)
        {
            if (role.Type == RoleType.LocalLead)
            {
                People localPeople = new People();

                RoleLookup allRoles = RoleLookup.FromGeographyAndOrganization(role.GeographyId, role.OrganizationId);

                Roles viceRoles  = allRoles[RoleType.LocalDeputy];
                Roles adminRoles = allRoles[RoleType.LocalAdmin];

                foreach (PersonRole localRole in viceRoles)
                {
                    localPeople.Add(localRole.Person);
                }

                foreach (PersonRole localRole in adminRoles)
                {
                    localPeople.Add(localRole.Person);
                }

                result = result.LogicalOr(localPeople);
            }
        }

        return(result);
    }
예제 #2
0
    static void Main()
    {
        People peopleCollection = new People(3);

        peopleCollection.Add("John", "Smith");
        peopleCollection.Add("Jim", "Johnson");
        peopleCollection.Add("Sue", "Rabon");

        Console.WriteLine("Displaying the entries in peopleCollection:");
        foreach (DictionaryEntry de in peopleCollection)
        {
            Console.WriteLine("{0} {1}", de.Key, de.Value);
        }

        Console.WriteLine();
        Console.WriteLine("Displaying the entries in the modified peopleCollection:");
        peopleCollection["Jim"] = "Jackson";
        peopleCollection.Remove("Sue");
        peopleCollection.Insert(0, "Fred", "Anderson");

        foreach (DictionaryEntry de in peopleCollection)
        {
            Console.WriteLine("{0} {1}", de.Key, de.Value);
        }
    }
예제 #3
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Learning .Net");

            Person person = new Person("Phani", 27);

            Console.WriteLine(person.Age);
            person.PropertyChanged += PropertyChange_Handler;

            person.Age = 28;

            People people = new People();

            people.Add(person);
            people.Add(new Person("Sai", 20));

            foreach (Person p in people)
            {
                Console.WriteLine(p.Name + p.Age);
            }

            string user = await PersonService.GetPerson();

            Console.WriteLine($"{user}");


            Console.ReadLine();

            // ref and out both take pass by reference.
            // ref is two way where as out will only assign back value
            // to the passed reference but can't be used as input.
        }
예제 #4
0
        /// <summary>
        ///     Get all person IDs that match a certain login token.
        /// </summary>
        /// <param name="loginToken">The login token to look for.</param>
        /// <returns>An array of person IDs.</returns>
        private static People GetPeopleByLoginToken(string loginToken)
        {
            People result = new People();

            SwarmDb database = SwarmDb.GetDatabaseForReading();

            // First, is the login token numeric? If so, add it as is and is a valid person.

            if (LogicServices.IsNumber(loginToken))
            {
                try
                {
                    int    personId = Int32.Parse(loginToken);
                    Person person   = Person.FromIdentity(personId);

                    // If we get here without exception, the login token is a valid person Id

                    result.Add(person);
                }
                catch (Exception)
                {
                    // Do nothing. In particular, do not add the person Id as a candidate.
                }
            }

            // Second, is the login token ten digits? If so, look for the person with this personal number.
            // This is specific to the Swedish PP.

            string cleanedNumber = LogicServices.CleanNumber(loginToken);

            if (cleanedNumber.Length == 10)
            {
                int[] personIds = database.GetObjectsByOptionalData(ObjectType.Person,
                                                                    ObjectOptionalDataType.PersonalNumber,
                                                                    cleanedNumber);

                foreach (int personId in personIds)
                {
                    result.Add(Person.FromIdentity(personId));
                }
            }

            // Third, look for a matching name. Expand the login token so that "R Falkv" will match "Rickard Falkvinge".
            // Only do this if the login token, excessive whitespace removed, is five characters or more.

            result = People.LogicalOr(result, People.FromNamePattern(loginToken));

            // Fourth, look for a matching email. Only do an exact match here.

            if (loginToken.Contains("@"))
            {
                result = People.LogicalOr(result, People.FromEmailPattern(loginToken));
            }

            return(result);
        }
예제 #5
0
    public void AddPerson()
    {
        Dictionary <string, long> humans = new Dictionary <string, long>()
        {
            { "katerina", 193232323232333323 },
            { "pesho", 20999499999999 }
        };
        People people = new People(humans);

        people.Add("Aneliq", 133000044444444);
        humans.Add("Aneliq", 133000044444444);

        Assert.That(people.PeopleInfo.Equals(humans));
        Assert.Throws <InvalidOperationException>(() => people.Add("Aneliq", 133000044444444), null);
    }
예제 #6
0
 private void MenuItem_Click_4(object sender, RoutedEventArgs e)
 {
     try
     {
         XmlSerializer  serializer = new XmlSerializer(typeof(List <Person>));
         OpenFileDialog dialog     = new OpenFileDialog();
         dialog.Filter = "xml file (*.xml)|*.xml";
         if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
         {
             FileStream    fs         = new FileStream(dialog.FileName, FileMode.Open);
             XmlSerializer xs         = new XmlSerializer(typeof(ObservableCollection <Person>));
             var           collection = xs.Deserialize(fs) as ObservableCollection <Person>;
             People.Clear();
             foreach (var p in collection)
             {
                 People.Add(p);
             }
             fs.Close();
         }
     }
     catch (Exception error)
     {
         Console.WriteLine(error.Message);
         System.Windows.MessageBox.Show("File could not be loaded", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
        public void CreateRandomStudents <T>(int nStudents, AlignedRectangle region) where T : IndividualIntelligence, new()
        {
            for (int i = 0; i < nStudents; ++i)
            {
                var newPerson = new Person(this, new Point(0, 0));
                newPerson.Intelligence = new T
                {
                    Owner = newPerson
                };

                while (true)
                {
                    double x = RandomGenerator.NextDouble(region.UpperLeft.X, region.LowerRight.X);
                    double y = RandomGenerator.NextDouble(region.UpperLeft.Y, region.LowerRight.Y);
                    Point  proposedPosition = new Point(x, y);
                    if (!HitsWall(proposedPosition, newPerson.PhysicalRadius) &&
                        !BreachesPersonalSpace(newPerson, proposedPosition))
                    {
                        newPerson.Position = proposedPosition;
                        People.Add(newPerson);
                        break;
                    }
                }
            }
        }
예제 #8
0
        public void AddEmployee(DateTime birthDate, string dni, string email, string name, int telephon, String Iban, int Pin, String Position, Decimal Salary)
        {
            Employee employee = new Employee(birthDate, dni, email, name, telephon, Iban, Pin, Position, Salary);

            People.Add(employee);
            Employees.Add(employee);
        }
예제 #9
0
        // CONSTRUCTORS
        public MainForm()
        {
            InitializeComponent();

            random        = new Random();
            people        = new People();
            filterControl = null;

            string[] names    = { "Bob", "John", "Sam", "David", "Adam" };
            string[] surnames = { "Ross", "Snow", "Davis", "Bowie", "Gontier" };

            for (int i = 0; i < 50000; ++i)
            {
                people.Add(new Person()
                {
                    Id      = i,
                    Name    = names[random.Next(names.Length)] + i,
                    Surname = surnames[random.Next(surnames.Length)] + i,
                    Age     = random.Next(1, 90)
                });
            }

            peopleView = new PeopleView(people);

            UpdateInterface();
        }
예제 #10
0
        //AnotherChildViewModel _anotherChildViewModel = (AnotherChildViewModel)IoC.GetInstance(typeof(AnotherChildViewModel), null);

        public HomeViewModel()
        {
            _thirdChild            = (ThirdChildViewModel)IoC.GetInstance(typeof(ThirdChildViewModel), null);
            _selectedPerson        = (PersonModel)IoC.GetInstance(typeof(PersonModel), null);
            _anotherChildViewModel = (AnotherChildViewModel)IoC.GetInstance(typeof(AnotherChildViewModel), null);
            _windowManager         = (IWindowManager)IoC.GetInstance(typeof(IWindowManager), null);

            //Adds new items to list people
            People.Add(new PersonModel {
                FirstName = "Will", LastName = "Smith"
            });
            People.Add(new PersonModel {
                FirstName = "Sue", LastName = "Johnes"
            });
            People.Add(new PersonModel {
                FirstName = "Robert", LastName = "Jackson"
            });

            _eventAggregator = (IEventAggregator)IoC.GetInstance(typeof(IEventAggregator), null);
            _eventAggregator.Subscribe(this);

            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    Task.Delay(1000).Wait();
                    Timer++;
                }
            });
        }
예제 #11
0
        private async Task LoadMoreAction(object arg)
        {
            if (IsLoading)
            {
                return;
            }

            IsLoading = true;

            try
            {
                var morePeople = await Service.GetPeople(nextPage.Substring(nextPage.IndexOf("page=")));

                foreach (var p in morePeople.PeopleList)
                {
                    People.Add(p);
                }

                nextPage    = morePeople.NextPage;
                HasNextPage = nextPage != null;
                OnPropertyChanged("People");
            }
            catch (Exception)
            {
                //TODO: Handle specific exception

                AlertHelper.ShowMessage("Error", AppResource.err_DataLoadMessage, "OK");
            }

            IsLoading = false;
        }
예제 #12
0
        private void AddPerson()
        {
            var newPerson = new PersonViewModel();

            newPerson.RemoveClicked += (p) => People.Remove(p);
            People.Add(newPerson);
        }
예제 #13
0
        private void AddPerson(Person person)
        {
            People.Add(new MergePerson(person));

            AddProperty("Photo", "Photo", person.Id,
                        person.PhotoId.HasValue ? person.PhotoId.ToString() : string.Empty,
                        Person.GetPhotoImageTag(person, 65, 65, "merge-photo"));
            AddProperty("Title", person.Id, person.TitleValue);
            AddProperty("FirstName", person.Id, person.FirstName);
            AddProperty("NickName", person.Id, person.NickName);
            AddProperty("MiddleName", person.Id, person.MiddleName);
            AddProperty("LastName", person.Id, person.LastName);
            AddProperty("Suffix", person.Id, person.SuffixValue);
            AddProperty("RecordType", person.Id, person.RecordTypeValue);
            AddProperty("RecordStatus", person.Id, person.RecordStatusValue);
            AddProperty("RecordStatusReason", person.Id, person.RecordStatusReasonValue);
            AddProperty("ConnectionStatus", person.Id, person.ConnectionStatusValue);
            AddProperty("Deceased", person.Id, person.IsDeceased);
            AddProperty("Gender", person.Id, person.Gender);
            AddProperty("MaritalStatus", person.Id, person.MaritalStatusValue);
            AddProperty("BirthDate", person.Id, person.BirthDate);
            AddProperty("AnniversaryDate", person.Id, person.AnniversaryDate);
            AddProperty("GraduationDate", person.Id, person.GraduationDate);
            AddProperty("Email", person.Id, person.Email);
            AddProperty("EmailActive", person.Id, person.IsEmailActive);
            AddProperty("EmailNote", person.Id, person.EmailNote);
            AddProperty("EmailPreference", person.Id, person.EmailPreference);
            AddProperty("InactiveReasonNote", person.Id, person.InactiveReasonNote);
            AddProperty("SystemNote", person.Id, person.SystemNote);
        }
예제 #14
0
        private void AddNewPerson()
        {
            var person = new Person();

            SelectedPerson = person;
            People.Add(person);
        }
예제 #15
0
 public void GeneratePeople(int numberOfPeople)
 {
     for (int i = People.Count; i < numberOfPeople; i++)
     {
         People.Add(new Person(this));
     }
 }
예제 #16
0
        void buttonOK_Click(object sender, EventArgs e)
        {
            try
            {
                if (_people.StateRecord == Nampula.DI.eState.eDatabase)
                {
                    Close();
                }


                _binds.FillClass(_people);

                if (_people.StateRecord == eState.eAdd)
                {
                    _people.Add();
                }
                else if (_people.StateRecord == eState.eUpdate)
                {
                    _people.Update();
                }

                _people.StateRecord = Nampula.DI.eState.eDatabase;
                SetTextButton(buttonOK, GetFormState(_people));
                ShowSucessfullMessage();
                _binds.FillControls(_people);
            }
            catch (Exception ex)
            {
                ShowMessageError(ex);
            }
        }
예제 #17
0
        public Person addPerson(Person person)
        {
            People.Add(person);
            this.SaveChanges();

            return(person);
        }
예제 #18
0
        private async Task InitAsync(Planet arg)
        {
            IsLoading = true;
            if (arg != null)
            {
                Planet = arg;
                Movies.Clear();
                foreach (var film in Planet.films)
                {
                    var currentFilm = await _filmRepository.GetFilmAsync(film) ??
                                      await _dataService.GetSingleByUrl <Film>(film);

                    Movies.Add(currentFilm);
                }
                Movies = Movies.OrderBy(item => item.episode_id).ToObservableCollection();

                People.Clear();
                foreach (var person in Planet.residents)
                {
                    var currentPerson = await _peopleRepository.GetPeopleAsync(person) ??
                                        await _dataService.GetSingleByUrl <People>(person);

                    People.Add(currentPerson);
                }
                People = People.OrderBy(item => item.name).ToObservableCollection();
            }
            IsLoading = false;
        }
예제 #19
0
        async Task ExecuteLoadItemsCommand()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;

            try
            {
                People.Clear();
                var items = await DataStore.GetItemsAsync(true);

                foreach (var item in items)
                {
                    People.Add(item);
                }
            }
            catch (Exception ex)
            {
                MessagingCenter.Send(this, "LoadException",
                                     $"Load failed, check your internet connection.\nDetails:\n{ex.Message}");
            }
            finally
            {
                IsBusy = false;
            }
        }
예제 #20
0
        /// <summary>
        /// 默认构造函数
        /// </summary>
        public Company()
        {
            // 实例化时对People成员进行初始化赋值,将人员列表赋给People集合
            List <string> s = SettingDataBase.ReadCompanyPeople();

            s.ForEach(i => People.Add(i));
        }
예제 #21
0
        public PersonSetting FindAddPerson(string requestedBy, int avatarCount = AVATAR_COUNT)
        {
            if (string.IsNullOrEmpty(requestedBy))
            {
                _log.Warn("Tried to add a person with a null RawName");
                return(null);
            }
            var person = FindPersonByRawName(requestedBy);

            if (person != null)
            {
                return(person);
            }
            person = new PersonSetting
            {
                DisplayName  = requestedBy,
                RawName      = requestedBy,
                FailedBuilds = 0,
                TotalBuilds  = 0,
                AvatarId     = People.Count % avatarCount
            };
            People.Add(person);
            Save();
            return(person);
        }
        async Task ExecuteLoadPeopleCommand()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;

            try
            {
                People.Clear();
                var listofPeople = await iDataService.GetPeopleAsync();

                foreach (var people in listofPeople)
                {
                    People.Add(people);
                }
            }
            catch (Exception exp)
            {
                Debug.WriteLine(exp.Message);
            }
            finally
            {
                IsBusy = false;
            }
        }
        private void ExecuteUpdateItemCommand()
        {
            // 新規登録
            if (Person.Id == 0)
            {
                Model.Person person = reverseMapper.Map <PersonViewModel, Model.Person>(Person);
                int          res    = personRepository.AddItem(person);

                if (res != 0)
                {
                    Person.Id = res;
                    People.Add(Person);
                    SelectedIndex = -1;
                }
            }
            // 修正
            else
            {
                Model.Person person = reverseMapper.Map <PersonViewModel, Model.Person>(Person);
                int          res    = personRepository.UpdateItem(person);

                if (res != 0)
                {
                    var per = People.Where(x => x.Id == person.Id).FirstOrDefault();
                    if (per != null)
                    {
                        per = mapper.Map <Model.Person, PersonViewModel>(person);
                    }
                }
            }
        }
예제 #24
0
        async Task ExecuteLoadItemsCommand()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;

            try
            {
                People.Clear();
                var people = await DataStore.GetItemsAsync(true);

                foreach (var person in people)
                {
                    People.Add(person);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
 public MainViewModel(IEnumerable <Model.Person> models)
 {
     foreach (var personModel in models)
     {
         People.Add(new PersonVm(personModel));
     }
 }
예제 #26
0
            private void UpdateList(PropertyChangedMessage <Person> obj)
            {
                var person         = obj.NewValue;
                var observedPerson = People.FirstOrDefault(i => i.Id == person.Id);

                //add person if new to persist
                if (observedPerson == null && !person.IsEmpty)
                {
                    People.Add(person);
                    _peopleService.AddPerson(person);
                }
                //if found and delete flag set
                if (person.Delete)
                {
                    People.Remove(person);
                    _peopleService.RemovePerson(person);
                }
                //if found, do an update
                else if (observedPerson != null)
                {
                    observedPerson.FirstName = person.FirstName;
                    observedPerson.LastName  = person.LastName;
                    observedPerson.Birthday  = person.Birthday;
                    observedPerson.Email     = person.Email;
                    observedPerson.Delete    = person.Delete;

                    _peopleService.UpdatePerson(person);
                }
            }
예제 #27
0
        void OnStartAddRemove()
        {
            if (AddRemoveActive)
            {
                AddRemoveTimer.Stop();
                AddRemoveActive = false;
                RaisePropertyChanged(nameof(AddButtonText));
                return;
            }

            AddRemoveActive         = true;
            AddRemoveTimer.Interval = TimeSpan.FromMilliseconds(RefreshInterval);
            RaisePropertyChanged(nameof(AddButtonText));

            AddRemoveTimer.Tick += (s, e) =>
            {
                WorldAction action = (WorldAction)Randomizer.Next(3);

                switch (action)
                {
                case WorldAction.Add:
                    People.Add(new Person()
                    {
                        Name = Names[Randomizer.Next(Names.Count)], Id = Names.Count, Worth = RandomCash()
                    });
                    break;

                case WorldAction.Remove:
                    People.RemoveAt(Randomizer.Next(People.Count));
                    break;
                }
                Application.Current.Dispatcher.Invoke(() => RaisePropertyChanged(nameof(People)));
            };
            AddRemoveTimer.Start();
        }
예제 #28
0
        public Employee AddEmployee(string firstName, string lastName, string password, IEnumerable <Permission> permissions)
        {
            Employee emp = new Employee(firstName, lastName, password, permissions);

            People.Add(emp);
            return(emp);
        }
예제 #29
0
 private void AddNewPerson()
 {
     People.Add(new PersonViewModel(new Person())
     {
         IsInEdit = true, IsNew = true
     });
 }
        public ListViewItemContextMenuBehaviourViewModel()
        {
            Title = "ListViewItemContextMenuBehaviour";

            People.Add(new PersonViewModel()
            {
                FirstName = "Homer", LastName = "Simpson"
            });
            People.Add(new PersonViewModel()
            {
                FirstName = "Marge", LastName = "Simpson"
            });
            People.Add(new PersonViewModel()
            {
                FirstName = "Bart", LastName = "Simpson"
            });
            People.Add(new PersonViewModel()
            {
                FirstName = "Lisa", LastName = "Simpson"
            });
            People.Add(new PersonViewModel()
            {
                FirstName = "Maggie", LastName = "Simpson"
            });
        }
예제 #31
0
    protected void ButtonSearch_Click (object sender, EventArgs e)
    {
        // If a member number is present, use only that as search criteria.

        People searchResults = null;

        string searchMemberNumber = this.TextMemberNumber.Text.Trim();

        if (searchMemberNumber.Length > 0)
        {
            // Lots of things here that will throw on invalid arguments
            Regex re = new Regex(@"[\s,;]+");
            string[] numbers = re.Replace(searchMemberNumber, ";").Split(';');
            searchResults = new People();
            foreach (string pers in numbers)
            {
                try
                {
                    string persID = pers;
                    if (searchMemberNumber.Trim().ToUpper().StartsWith("PP"))
                    {
                        //Hexcoded number
                        char[] mnr = persID.Substring(2).ToCharArray();
                        Array.Reverse(mnr);
                        persID = new string(mnr);
                        int num = (System.Int32.Parse(searchMemberNumber, System.Globalization.NumberStyles.AllowHexSpecifier));
                        persID = num.ToString();
                    }
                    int personId = Convert.ToInt32(persID);
                    Person person = Person.FromIdentity(personId);
                    searchResults.Add(person);
                }
                catch (Exception)
                { }
            }

            if (numbers.Length > 1)
            {
                PersonList.GridView.PageSize = numbers.Length;
                PersonList.ShowStreet = true;
            }
        }
        else
        {
            People nameResult = People.FromNamePattern(TextNamePattern.Text);
            People emailResult = People.FromEmailPattern(TextEmailPattern.Text);
            People cityResult = People.FromCityPattern(TextCityPattern.Text);
            People pcResult = People.FromPostalCodePattern(TextPostalCodePattern.Text);

            if (nameResult != null || emailResult != null)
            {
                searchResults = People.LogicalAnd(nameResult, emailResult);
            }
            if (searchResults != null || cityResult != null)
            {
                searchResults = People.LogicalAnd(searchResults, cityResult);
            }
            if (searchResults != null || pcResult != null)
            {
                searchResults = People.LogicalAnd(searchResults, pcResult);
            }

            string inputDateText = textPersonalNumber.Text.Trim();
            if (inputDateText != "")
            {
                int inpLen = inputDateText.Length;
                int yLen = 2;

                string[] formats2 = new string[] { "yy", "yyMM", "yyMMdd", "yyyy", "yyyyMM", "yyyyMMdd", "yyyy", "yyyy-MM", "yyyy-MM-dd", "yy", "yy-MM", "yy-MM-dd" };
                string[] formats4 = new string[] { "yyyy", "yyyyMM", "yyyyMMdd", "yy", "yyMM", "yyMMdd", "yyyy", "yyyy-MM", "yyyy-MM-dd", "yy", "yy-MM", "yy-MM-dd" };
                string[] formats;

                DateTime parsedDate = DateTime.MinValue;
                DateTime endDate = DateTime.MaxValue;

                if (inputDateText.StartsWith("19")
                    || inputDateText.StartsWith("20"))
                {
                    formats = formats4;
                    yLen = 4;
                }
                else
                    formats = formats2;
                string[] datesSplit = (textPersonalNumber.Text + "--").Split(new string[] { "--" }, StringSplitOptions.None);

                DateTime.TryParseExact(datesSplit[0].Trim(), formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate);
                if (parsedDate != DateTime.MinValue)
                {
                    if (datesSplit[1] != "")
                    {
                        DateTime.TryParseExact(datesSplit[1].Trim(), formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out endDate);
                        inpLen = datesSplit[1].Trim().Length;
                        bool dash = textPersonalNumber.Text.Contains("-");
                        if (inpLen == yLen)
                        {
                            endDate = endDate.AddYears(1);
                        }
                        else if (inpLen == yLen + 2 || (dash && inpLen == yLen + 3))
                        {
                            endDate = endDate.AddMonths(1);
                        }
                        else
                            endDate = endDate.AddDays(1);
                    }
                    else
                    {
                        inpLen = datesSplit[0].Trim().Length;
                        bool dash = textPersonalNumber.Text.Contains("-");
                        if (inpLen == yLen)
                        {
                            endDate = parsedDate.AddYears(1);
                        }
                        else if (inpLen == yLen + 2 || (dash && inpLen == yLen + 3))
                        {
                            endDate = parsedDate.AddMonths(1);
                        }
                        else
                            endDate = parsedDate.AddDays(1);
                    }

                    People dateResults = People.FromBirtDatePattern(parsedDate, endDate);
                    if (searchResults != null || dateResults != null)
                    {
                        searchResults = People.LogicalAnd(searchResults, dateResults);
                    }
                }
            }
        }

        if (searchResults != null && CheckBoxActivist.Checked)
        {
            //Activism can't be searched for in itself. Too heavy on the DB.

            searchResults = searchResults.Filter(
                delegate(Person p)
                {
                    if (p.IsActivist)
                        return true;
                    else
                        return false;
                });
        }


        if (searchResults != null)
        {
            PersonList.ShowStatus = false;

            Authority auth = _authority;

            //TODO: All this supposes that these permissions can be applied to mon swedish people as well, ie Organization.PPSEid is supposed
            if (auth.HasPermission(Permission.CanSeeNonMembers,Organization.PPSEid,-1,Authorization.Flag.AnyGeographyExactOrganization) )
                PersonList.ShowStatus = true;

            if (!auth.HasPermission(Permission.CanValidateActivistEmail, Organization.PPSEid, -1, Authorization.Flag.AnyGeographyExactOrganization) || searchResults.Count > 5)
            {
                // SERIOUS SECURITY BREACH here: All chairmen for all organizations could see ALL members.
                // "CanValidateActivistEmail" was set for "OrganizationChairman".

                searchResults = searchResults.GetVisiblePeopleByAuthority(auth);
            }
            else
            {
                PersonList.ShowStatus = true;
            }


            if (!auth.HasPermission(Permission.CanValidateActivistEmail, Organization.PPSEid, -1, Authorization.Flag.AnyGeographyExactOrganization) || searchResults.Count > 1)
            {
                // SERIOUS SECURITY BREACH here: All chairmen for all organizations could see ALL members.
                // "CanValidateActivistEmail" was set for "OrganizationChairman".

                searchResults = searchResults.RemoveUnlisted();
            }
            PersonList.PersonList = searchResults;
        }
    }
예제 #32
0
        internal static void ProcessParleyCancelled (BasicPWEvent newPwEvent)
        {
            Parley parley = Parley.FromIdentity(newPwEvent.ParameterInt);
            Person actingPerson = Person.FromIdentity(newPwEvent.ActingPersonId);

            string body = "Regrettably, conference #" + parley.Identity + " (" + parley.Name +
                          "), organized by " + parley.Organization.Name + " and scheduled for " + parley.StartDate.ToString("yyyy-MM-dd") + ", has been cancelled. You were one of the attending people.\r\n\r\n";

            body +=
                "If you have received an invoice for your participation in this conference, you will receive a credit invoice shortly. If you have received an invoice and already paid your attendance fee, that fee will be reimbursed shortly as part of the crediting process. " +
                "You will get separate notices as this happens.\r\n\r\n" +

                "We apologize deeply for the inconvenience.\r\n";


            ParleyAttendees attendees = parley.Attendees;

            People concernedPeople = new People();

            foreach (ParleyAttendee attendee in attendees)
            {
                concernedPeople.Add(attendee.Person);
            }

            new MailTransmitter(Strings.MailSenderNameFinancial, "*****@*****.**",   // HACK - must use organization's address and name
                                           "Conference CANCELLED: " + parley.Name,
                                           body, concernedPeople, false).Send();

            foreach (ParleyAttendee attendee in attendees)
            {
                if (attendee.Invoiced && attendee.OutboundInvoiceId > 0)
                {
                    if (attendee.Invoice.CreditInvoice == null)
                    {
                        attendee.Invoice.Credit(actingPerson);
                    }
                }
            }

            parley.CancelBudget();
            parley.CloseBudget(actingPerson);
            parley.Open = false;
        }
예제 #33
0
        private static void ProcessLocalDonationReceived (BasicPWEvent newPwEvent)
        {
            Organization organization = Organization.FromIdentity(newPwEvent.OrganizationId);
            Geography geography = Geography.FromIdentity(newPwEvent.GeographyId);
            FinancialAccount account = FinancialAccount.FromIdentity(Int32.Parse(newPwEvent.ParameterText));
            FinancialTransaction transaction = FinancialTransaction.FromIdentity(newPwEvent.ParameterInt);
            CultureInfo culture = new CultureInfo(organization.DefaultCountry.Culture);

            DateTime today = DateTime.Today;
            Int64 amount = transaction.Rows[0].AmountCents;  // just pick any transaction row, it'll have the amount
            Int64 budget = -(account.GetBudgetCents(DateTime.Today.Year));
            Int64 curBalance = account.GetDeltaCents(new DateTime(today.Year, 1, 1), new DateTime(today.Year, 12, 31));

            Int64 fundsAvailable = budget - curBalance;

            if (amount < 0)
            {
                amount = -amount;  // though possibly in the negative so let's make sure it's positive
            }

            // Assemble notification body

            string body =
                "Local donation received for " + organization.Name + ", " + geography.Name + ":\r\n\r\n";

            body += amount.ToString("N2", culture) + " received on " +
                    transaction.DateTime.ToString("yyyy-MMM-dd") + ".\r\n\r\n";

            body += "Total funds available in the local budget: " + (fundsAvailable/100.0).ToString("N2", culture) + ".\r\n";

            // Determine who to send to (local leads and vices, plus Rick for debugging)

            People concernedPeople = new People();

            RoleLookup lookup = RoleLookup.FromGeographyAndOrganization(geography, organization);

            Roles leadRoles = lookup[RoleType.LocalLead];
            Roles viceRoles = lookup[RoleType.LocalDeputy];

            if (leadRoles.Count > 0)
            {
                concernedPeople.Add(leadRoles[0].Person);  // should only be one lead
            }
            foreach (PersonRole role in viceRoles)
            {
                concernedPeople.Add(role.Person);
            }

            // add Rick

            concernedPeople.Add(Person.FromIdentity(1));

            new MailTransmitter(Strings.MailSenderNameFinancial, Strings.MailSenderAddress,
                               "Local donation received: [" + amount.ToString("N2", culture) + "]",
                               body, concernedPeople, true).Send();
        }
예제 #34
0
    protected People GetDirectReports ()
    {
        People result = new People();

        foreach (BasicPersonRole role in _authority.LocalPersonRoles)
        {
            if (role.Type == RoleType.LocalLead || role.Type == RoleType.LocalDeputy || role.Type == RoleType.LocalAdmin)
            {
                Geographies geographies = Geography.FromIdentity(role.GeographyId).Children;

                // HACK: Compensate for current bad tree structure

                if (role.GeographyId == 34)
                { //Lägg till Skåne till Södra
                    geographies = geographies.LogicalOr(Geography.FromIdentity(36).Children);
                }

                if (role.GeographyId == 32)
                { //Lägg till Västra Götaland till Västra
                    geographies = geographies.LogicalOr(Geography.FromIdentity(355).Children);
                }

                foreach (Geography geography in geographies)
                {
                    People localLead = new People();
                    RoleLookup allRoles = RoleLookup.FromGeographyAndOrganization(geography.Identity,
                                                                                  role.OrganizationId);

                    Roles leadRoles = allRoles[RoleType.LocalLead];

                    foreach (PersonRole leadRole in leadRoles)
                    {
                        localLead.Add(leadRole.Person);
                    }

                    result = result.LogicalOr(localLead);
                }
            }
        }

        return result;
    }
예제 #35
0
    /* Fix for Ticket #64 - Vice på distrikt- och valkretsnivå bör kunna assigna användare 
     * som är tilldelade Lead, för att avlasta varandra och undvika flaskhalsar. */
    protected People GetLeadsVicesAndAdmins ()
    {
        People result = new People();

        foreach (BasicPersonRole role in _authority.LocalPersonRoles)
        {
            if (role.Type == RoleType.LocalLead || role.Type == RoleType.LocalDeputy)
            {
                People localPeople = new People();

                RoleLookup allRoles = RoleLookup.FromGeographyAndOrganization(role.GeographyId, role.OrganizationId);

                Roles leadRoles = allRoles[RoleType.LocalLead];
                Roles viceRoles = allRoles[RoleType.LocalDeputy];
                Roles adminRoles = allRoles[RoleType.LocalAdmin];

                foreach (PersonRole localRole in leadRoles)
                {
                    localPeople.Add(localRole.Person);
                }

                foreach (PersonRole localRole in viceRoles)
                {
                    localPeople.Add(localRole.Person);
                }

                foreach (PersonRole localRole in adminRoles)
                {
                    localPeople.Add(localRole.Person);
                }

                result = result.LogicalOr(localPeople);
            }
        }

        return result;
    }
예제 #36
0
        public static People FilterPeopleToMatchAuthority (People people, Authority authority, int gracePeriod)
        {
            // First: If sysadmin, return the whole list uncensored.

            if (IsSystemAdministrator(authority))
            {
                return people;
            }

            SwarmDb databaseRead = SwarmDb.GetDatabaseForReading();

            if (gracePeriod == -1)
                gracePeriod = Membership.GracePeriod;

            Dictionary<int, List<BasicMembership>> membershipTable = databaseRead.GetMembershipsForPeople(people.Identities, gracePeriod);
            Dictionary<int, int> geographyTable = databaseRead.GetPeopleGeographies(people.Identities);

            var clearedPeople = new Dictionary<int, Person>();


            // Clear by organization roles 
            bool CanSeeNonMembers = authority.HasPermission(Permission.CanSeeNonMembers,Organization.PPSEid,-1,Flag.AnyGeographyExactOrganization);

            foreach (BasicPersonRole role in authority.OrganizationPersonRoles)
            {
                Dictionary<int, BasicOrganization> clearedOrganizations =
                    OrganizationCache.GetOrganizationHashtable(role.OrganizationId);

                foreach (Person person in people)
                {
                    // Is the organization cleared in this officer's role for this to-be-viewed member?

                    if (membershipTable.ContainsKey(person.Identity))
                    {
                        foreach (BasicMembership membership in membershipTable[person.Identity])
                        {
                            if (clearedOrganizations.ContainsKey(membership.OrganizationId)
                                && authority.HasPermission(Permission.CanSeePeople, membership.OrganizationId, person.GeographyId, Flag.Default))
                            {
                                if (membership.Active
                                    || (membership.Expires > DateTime.Now.AddDays(-gracePeriod)
                                        && membership.Expires.AddDays(1) > membership.DateTerminated
                                        && authority.HasPermission(Permission.CanSeeExpiredDuringGracePeriod, membership.OrganizationId, person.GeographyId, Flag.Default)))
                                {
                                    clearedPeople[person.Identity] = person;
                                    break;
                                }
                            }
                        }
                    }
                    else if (CanSeeNonMembers)
                    { //person isn't member anywhere
                        clearedPeople[person.Identity] = person;
                    }
                }
            }


            // Clear by node roles:
            //
            // For each node role, check if each member is in a cleared geography AND a cleared organization.
            // If so, permit view of this member. (A person in a branch of a geographical area for organizations X and Z
            // should see only people of those organizations only on those nodes.)


            foreach (BasicPersonRole role in authority.LocalPersonRoles)
            {
                Dictionary<int, BasicGeography> clearedGeographies = GeographyCache.GetGeographyHashtable(role.GeographyId);
                Dictionary<int, BasicOrganization> clearedOrganizations = OrganizationCache.GetOrganizationHashtable(role.OrganizationId);

                foreach (Person person in people)
                {

                    // Is the node AND the organization cleared in this officer's role for this to-be-viewed member?

                    if (membershipTable.ContainsKey(person.Identity))
                    {
                        foreach (BasicMembership membership in membershipTable[person.Identity])
                        {
                            int organizationClear = 0;
                            int geographyClear = 0;
                            if (clearedOrganizations.ContainsKey(membership.OrganizationId))
                            {
                                organizationClear = membership.OrganizationId;

                                if (clearedGeographies.ContainsKey(geographyTable[person.Identity]))
                                {
                                    geographyClear = geographyTable[person.Identity];
                                }

                                if (organizationClear > 0
                                    && geographyClear > 0
                                    && authority.HasPermission(Permission.CanSeePeople, organizationClear, geographyClear, Flag.Default))
                                {
                                    if (membership.Active
                                        || (membership.Expires > DateTime.Now.AddDays(-gracePeriod)
                                            && membership.Expires.AddDays(1) > membership.DateTerminated
                                            && authority.HasPermission(Permission.CanSeeExpiredDuringGracePeriod, membership.OrganizationId, person.GeographyId, Flag.Default)))
                                    {
                                        clearedPeople[person.Identity] = person;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }



            // End: Assemble an array of the resulting cleared people

            var result = new People();

            foreach (Person clearedPerson in clearedPeople.Values)
            {
                result.Add(clearedPerson);
            }

            return result;
        }
 // Event handlers for menu items.
 void NewOnExecuted(object sender, ExecutedRoutedEventArgs args)
 {
     people = new People();
     people.Add(new Person());
     InitializeNewPeopleObject();
 }
예제 #38
0
        static private People ApplySubscription (People input, int feedId)
        {
            People output = new People();

            foreach (Person person in input)
            {
                if (person.IsSubscribing(feedId))
                {
                    output.Add(person);
                }
            }

            return output;
        }
예제 #39
0
        /// <summary>
        /// Get all person IDs that match a certain login token.
        /// </summary>
        /// <param name="loginToken">The login token to look for.</param>
        /// <returns>An array of person IDs.</returns>
        private static People GetPeopleByLoginToken (string loginToken)
        {
            People result = new People();

            SwarmDb database = SwarmDb.GetDatabaseForReading();

            // First, is the login token numeric? If so, add it as is and is a valid person.

            if (LogicServices.IsNumber(loginToken))
            {
                try
                {
                    int personId = Int32.Parse(loginToken);
                    Person person = Person.FromIdentity(personId);

                    // If we get here without exception, the login token is a valid person Id

                    result.Add(person);
                }
                catch (Exception)
                {
                    // Do nothing. In particular, do not add the person Id as a candidate.
                }
            }

            // Second, is the login token ten digits? If so, look for the person with this personal number.
            // This is specific to the Swedish PP.

            string cleanedNumber = LogicServices.CleanNumber(loginToken);

            if (cleanedNumber.Length == 10)
            {
                int[] personIds = database.GetObjectsByOptionalData(ObjectType.Person,
                                                                    ObjectOptionalDataType.PersonalNumber,
                                                                    cleanedNumber);

                foreach (int personId in personIds)
                {
                    result.Add(Person.FromIdentity(personId));
                }
            }

            // Third, look for a matching name. Expand the login token so that "R Falkv" will match "Rickard Falkvinge".
            // Only do this if the login token, excessive whitespace removed, is five characters or more.

            result = People.LogicalOr(result, People.FromNamePattern(loginToken));

            // Fourth, look for a matching email. Only do an exact match here.

            if (loginToken.Contains("@"))
            {
                result = People.LogicalOr(result, People.FromEmailPattern(loginToken));
            }

            return result;
        }