예제 #1
0
        private async void FetchPersonGroup_Click(object sender, RoutedEventArgs e)
        {
            personGroupId = "enter your group ID here"
                            personGroupName       = "enter your group name";
            PersonGroupStatusTextBlock.Foreground = new SolidColorBrush(Colors.Black);
            authKey = "enter your azure key";

            await ApiCallAllowed(true);

            faceServiceClient = new FaceServiceClient(authKey);

            if (null != faceServiceClient)
            {
                // You may experience issues with this below call, if you are attempting connection with
                // a service location other than 'West US'
                PersonGroup[] groups = await faceServiceClient.ListPersonGroupsAsync();

                var matchedGroups = groups.Where(p => p.PersonGroupId == personGroupId);

                if (matchedGroups.Count() > 0)
                {
                    knownGroup = matchedGroups.FirstOrDefault();

                    PersonGroupStatusTextBlock.Text = "Joined Group: " + knownGroup.Name; //"Please enter the following details below";// + knownGroup.Name;//"Successfully Joined Social Lens";//
                }

                if (null == knownGroup)
                {
                    PersonGroupStatusTextBlock.Text = "Could not find group. Make sure that you have entered the proper group name ";// + knownGroup.Name;
                }
                PersonGroupStatusTextBlock.Foreground = new SolidColorBrush(Colors.Green);
            }
        }
예제 #2
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log, ExecutionContext context)
        {
            #region Config
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            var faceEndpoint    = config["faceEndpoint"];
            var subscriptionKey = config["faceSubscriptionKey"];
            #endregion

            #region Read Body
            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);
            string  imageUrl    = data?.imageUrl;
            string  personName  = data?.personName;
            string  personId    = data?.personId;
            #endregion

            #region Cognitive Services Calls
            FaceClient faceClient = new FaceClient(new ApiKeyServiceClientCredentials(subscriptionKey), new System.Net.Http.DelegatingHandler[] { })
            {
                Endpoint = faceEndpoint
            };

            //Sample Person Group is created at first run for demo purposes.
            //await faceClient.PersonGroup.CreateAsync(PersonGroupId, PersonGroupId);
            PersonGroup humanGroup = await faceClient.PersonGroup.GetAsync(PersonGroupId);

            Person human = null;
            if (string.IsNullOrEmpty(personId))
            {
                human = await faceClient.PersonGroupPerson.CreateAsync(humanGroup.PersonGroupId, personName);
            }
            else
            {
                human = await faceClient.PersonGroupPerson.GetAsync(humanGroup.PersonGroupId, new System.Guid(personId));
            }

            PersistedFace face = await faceClient.PersonGroupPerson.AddFaceFromUrlAsync(humanGroup.PersonGroupId, human.PersonId, imageUrl);

            await faceClient.PersonGroup.TrainAsync(PersonGroupId);

            #endregion

            #region Return JSON
            var myObj        = new { faceId = face.PersistedFaceId, personId = human.PersonId };
            var jsonToReturn = JsonConvert.SerializeObject(myObj);

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(jsonToReturn, Encoding.UTF8, "application/json")
            });

            #endregion
        }
예제 #3
0
        /// <summary>
        /// Attempts to Identify the given <see cref="Face"/> list <c>detectedFaces</c> against a trained <see cref="PersonGroup"/> containing 1 or more faces.
        /// </summary>
        /// <returns>A list of <see cref="IdentificationResult"/> containing <see cref="CandidateResult"/> indicating potential identification matches and the confidence factor for the match.</returns>
        /// <param name="personGroup">The <see cref="PersonGroup"/> to identify a <see cref="Face"/> against.</param>
        /// <param name="detectedFaces">A list of detected faces to use for the identification.</param>
        /// <param name="maxNumberOfCandidates">The max number of candidate matches to return.</param>
        public async Task <List <IdentificationResult> > Identify(PersonGroup personGroup, IEnumerable <Model.Face> detectedFaces, int maxNumberOfCandidates = 1)
        {
            try
            {
                //ensure people are loaded for this group
                await GetPeopleForGroup(personGroup);

                var detectedFaceIds = detectedFaces.Select(f => f.Id).ToArray();

                var results = await Identify(personGroup.Id, detectedFaceIds, maxNumberOfCandidates);

                System.Diagnostics.Debug.Assert(results.Count <= detectedFaces.Count(), "Number of detected faces passed in expected to be equal or more than the returned result count");

                for (int i = 0; i < results.Count; i++)
                {
                    var result = results [i];
                    result.Face = detectedFaces.ElementAt(i);

                    foreach (var candidate in result.CandidateResults)
                    {
                        candidate.Person = await GetPerson(personGroup, candidate.PersonId);
                    }
                }

                return(results);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                throw;
            }
        }
예제 #4
0
        private void itemsControl_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (CurrentViewMode == MainControls.CurrentViewMode.ArtistDetails ||
                CurrentViewMode == MainControls.CurrentViewMode.ComposerDetails)
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    ListBoxItem item = VisualTreeExtensions.FindParent <ListBoxItem>(e.OriginalSource as DependencyObject);
                    if (item != null)
                    {
                        TrackListItem tli         = item.DataContext as TrackListItem;
                        PersonGroup   personGroup = DataBase.GetPersonGroupByName(tli.Name, false);

                        PersonGroupWindow personGroupWindow = new PersonGroupWindow(DataBase,
                                                                                    CurrentViewMode == MainControls.CurrentViewMode.ArtistDetails ? PersonType.Artist : PersonType.Composer,
                                                                                    personGroup);
                        personGroupWindow.ChangeAllSoundFiles = true;
                        personGroupWindow.Owner = Window.GetWindow(this);
                        personGroupWindow.ShowDialog();

                        UpdateTrackListItem(tli);
                    }
                }
            }
        }
예제 #5
0
            public PersonGridViewAdapter(PersonGroup personGroup, Context context)
            {
                this.personGroup = personGroup;
                this.context     = context;

                ResetCheckedItems();
            }
예제 #6
0
        private ObservableCollection <PersonGroup> BuildModelForSample()
        {
            var model       = new ObservableCollection <PersonGroup>();
            var emailSource = new ComplexEmailSource();

            var alex     = new Person("Alex", emailSource);
            var beatrice = new Person("Beatrice", emailSource);

            var swimmers = new PersonGroup("Swimmers");

            model.Add(swimmers);

            swimmers.Persons.Add(alex);
            swimmers.Persons.Add(beatrice);

            var cooks = new PersonGroup("Cooks");

            model.Add(cooks);
            cooks.Persons.Add(alex);

            var softwareEngineers = new PersonGroup("Software Engineers");

            model.Add(softwareEngineers);

            return(model);
        }
예제 #7
0
        /// <summary>
        /// Creates the <see cref="PersonGroup"/> with the given name and (optionally) custom user data.
        /// </summary>
        /// <returns>The person group.</returns>
        /// <param name="groupName">The name of the new group.</param>
        /// <param name="userData">A custom user data string to store with the group.</param>
        public async Task <PersonGroup> CreatePersonGroup(string groupName, string userData = null)
        {
            try
            {
                var personGroupId = Guid.NewGuid().ToString();

                await CreatePersonGroup(personGroupId, groupName, userData);

                var personGroup = new PersonGroup
                {
                    Name     = groupName,
                    Id       = personGroupId,
                    UserData = userData,
                    People   = new List <Person> ()
                };

                Groups.Add(personGroup);

                return(personGroup);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                throw;
            }
        }
예제 #8
0
        //PUT create person group
        public async Task <HttpResponseMessage> CreatePersonGroupAsync(string GroupID, string GroupName, string GroupDescription)
        {
            try
            {
                using (var client = FaceClient())
                {
                    string uri = AppSettings.baseuri + "/persongroups/" + GroupID;

                    // Request body
                    PersonGroup pg = new PersonGroup()
                    {
                        name = GroupName, userData = GroupDescription
                    };
                    string jsonRequest = JsonConvert.SerializeObject(pg);

                    content = new StringContent(jsonRequest);
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                    responseMessage = await client.PutAsync(uri, content);
                }
            }
            catch (Exception ex)
            {
            }
            return(responseMessage);
        }
예제 #9
0
        void ReloadData()
        {
            TableView.ReloadData();

            if (IsInitialLoad)
            {
                if (AutoSelect)
                {
                    if (Groups.Count == 1)
                    {
                        TableView.SelectRow(TableView.IndexPathsForVisibleRows [0], true, UITableViewScrollPosition.Top);
                        SelectedPersonGroup = Groups [TableView.IndexPathForSelectedRow.Row];
                    }
                }
            }
            else if (SelectedPersonGroup != null && RestoreSelectionOnAppear)
            {
                var selectedIndex = Groups.IndexOf(SelectedPersonGroup);

                if (selectedIndex > -1)
                {
                    TableView.SelectRow(NSIndexPath.FromRowSection(selectedIndex, 0), true, UITableViewScrollPosition.Top);
                }
            }
        }
        private async void CreatePersonGroupIfNotExists(string personGroupId, string personGroupName)
        {
            var         faceServiceClient = CreateAzureClient();
            PersonGroup personGroup       = null;

            try
            {
                personGroup = await faceServiceClient.GetPersonGroupAsync(personGroupId.ToLowerInvariant());
            }
            catch (FaceAPIException e)
            {
            }

            try
            {
                if (personGroup == null)
                {
                    await faceServiceClient.CreatePersonGroupAsync(personGroupId.ToLowerInvariant(), personGroupName);

                    Log.Info($"Created person group " + personGroupId, this);
                }
                else
                {
                    Log.Info($"Person group already exists - " + personGroupId, this);
                }
            }
            catch (FaceAPIException e)
            {
                Log.Info("Exception during creating person group" + e.ToString(), this);
                throw;
            }
        }
예제 #11
0
        public async Task <IActionResult> Edit(int id, [Bind("Name,LatinName,Id,UserId,LogRecordId,Status,ModDateTime,ModByUserId,Comment")] PersonGroup personGroup)
        {
            if (id != personGroup.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(personGroup);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PersonGroupExists(personGroup.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(_mapper.Map <PersonGroupViewModel>(personGroup)));
        }
예제 #12
0
        private async void frmAddFace_Load(object sender, EventArgs e)
        {
            await _options.UpdateMemberVarsFromProperties();

            string            CSKey      = _options.CSKey;
            FaceServiceClient faceClient = _options._faceServiceClient;

            // call our general library to get our list of groups and populate our combobox
            PersonGroup[] groups = await GenLib.GetPersonGroups(CSKey, faceClient);

            cmbPersonGroup.Items.Add(string.Empty);
            for (int i = 0; i < groups.Length; i++)
            {
                PersonGroup personGroup = groups[i];
                cmbPersonGroup.Items.Add(personGroup);
                //cmbPersonGroup.Items.Add(personGroup.PersonGroupId);
            }

            //cmbPersonGroup.Items.AddRange(groups);

            // select first group by default
            if (groups.Length > 0)
            {
                if (cmbPersonGroup.Items.Count > 0)
                {
                    cmbPersonGroup.SelectedIndex = 1;
                }
            }
        }
        public static bool PeopleMatch(Person forPerson, List <long> personsInSchedule)
        {
            List <long> personInConstraint = new List <long>();

            if (forPerson.Self is PersonGroup)
            {
                PersonGroup pGroup = (PersonGroup)forPerson.Self;
                personInConstraint = pGroup.Users.Select(a => a.Id).ToList();
            }
            else if (forPerson.Self is IndividualPerson)
            {
                IndividualPerson iPerson = (IndividualPerson)forPerson.Self;
                personInConstraint.Add(iPerson.Person.Id);
            }
            var diff = personInConstraint.Intersect(personsInSchedule);

            if (diff.Count() > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #14
0
            public async Task InitFaceGroup(string id, string name = null)
            {
                if (name == null)
                {
                    name = id;
                }

                try
                {
                    PersonGroup group = await _faceClient.PersonGroup.GetAsync(id);
                }
                catch (APIErrorException ex)
                {
                    if (ex.Body.Error.Code == "PersonGroupNotFound")
                    {
                        await _faceClient.PersonGroup.CreateAsync(id, name);

                        await _faceClient.PersonGroup.TrainAsync(id);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
예제 #15
0
        /// <summary>
        /// Gets the group's list of <see cref="Person"/>.
        /// </summary>
        /// <returns>A list of <see cref="Person"/> for the group.</returns>
        /// <param name="personGroup"><see cref="PersonGroup"/> to get people for.</param>
        /// <param name="forceRefresh">If set to <c>true</c>, force refresh of the cached list of people for this group.  This forces all people for this group to reload from the server and clears the currently cached list of people for this group.</param>
        public async Task <List <Person> > GetPeopleForGroup(PersonGroup personGroup, bool forceRefresh = false)
        {
            try
            {
                if (personGroup.People?.Count > 0 && !forceRefresh)
                {
                    return(personGroup.People);
                }

                var people = await GetPeopleForGroup(personGroup.Id);

                if (personGroup.PeopleLoaded)
                {
                    personGroup.People.Clear();
                    personGroup.People.AddRange(people);
                }
                else
                {
                    personGroup.People = people;
                }

                return(people);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                throw;
            }
        }
예제 #16
0
        private async Task <PersonGroup> CreatePersonGroupAsync()
        {
            // Always the same persongroup
            // Works somewhat like a server side singleton
            PersonGroup personGroup = new PersonGroup
            {
                personGroupId    = "default_id",
                name             = "default_group",
                userData         = "Default group, every property is hard-coded.",
                recognitionModel = "recognition_02"
            };

            var requestString =
                $@"{{
                ""name"": ""{personGroup.name}"",
                ""userData"": ""{personGroup.userData}"",
                ""recognitionModel"": ""{personGroup.recognitionModel}""
                }}";

            var byteContent = Encoding.UTF8.GetBytes(requestString);

            using (ByteArrayContent content = new ByteArrayContent(byteContent))
            {
                content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/json");

                var response = await client.PutAsync(uriBase + personGroupUri + $"/{personGroup.personGroupId}", content);

                // Proper Face API error check
                await CheckResponseAsync(response);

                return(personGroup);
            }
        }
예제 #17
0
        /// <summary>
        /// Creates a <see cref="Person"/> with the given name and (optionally) custom user data.
        /// </summary>
        /// <returns>The person.</returns>
        /// <param name="personName">The name of the new person.</param>
        /// <param name="personGroup">The <see cref="PersonGroup"/> this person will be a part of.</param>
        /// <param name="userData">A custom user data string to store with the person.</param>
        public async Task <Person> CreatePerson(string personName, PersonGroup personGroup, string userData = null)
        {
            try
            {
                var id = await CreatePerson(personName, personGroup.Id, userData);

                if (string.IsNullOrEmpty(id))
                {
                    throw new Exception("CreatePerson Result returned null or empty person Id");
                }

                var person = new Person
                {
                    Name     = personName,
                    Id       = id,
                    UserData = userData
                };

                if (personGroup.PeopleLoaded)
                {
                    personGroup.People.Add(person);
                }

                return(person);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                throw;
            }
        }
예제 #18
0
        private IEnumerable <PersonGroup> GetGroups()
        {
            PersonGroup currentGroup = null;

            foreach (var line in Lines)
            {
                if (line.Trim().Length == 0)
                {
                    yield return(currentGroup);

                    currentGroup = null;
                }
                else
                {
                    currentGroup ??= new PersonGroup();

                    currentGroup.Add(new Person(line));
                }
            }

            if (currentGroup != null)
            {
                yield return(currentGroup);
            }
        }
예제 #19
0
        /// <summary>
        /// Gets the <see cref="Person"/> with the specified Id and belonging to the given <see cref="PersonGroup"/>.
        /// </summary>
        /// <returns>The <see cref="Person"/>.</returns>
        /// <param name="personGroup">The <see cref="PersonGroup"/> the person is a part of.</param>
        /// <param name="personId">The Id of the <see cref="Person"/> to get.</param>
        public async Task <Person> GetPerson(PersonGroup personGroup, string personId)
        {
            //if people are already loaded for this group try to find it there...
            if (personGroup.PeopleLoaded)
            {
                var person = personGroup.People.FirstOrDefault(p => p.Id == personId);

                if (person != null)
                {
                    return(person);
                }
            }

            try
            {
                var person = await GetPerson(personGroup.Id, personId);

                //add them to the group?
                if (personGroup.PeopleLoaded)
                {
                    personGroup.People.Add(person);
                }

                return(person);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                throw;
            }
        }
예제 #20
0
        public bool AddHapagMatchingRolesAndProfiles(PersonGroup personGroup, User user)
        {
            var addedProfile = false;
            var addedRole    = false;

            if (_hapagProfiles.ContainsKey(personGroup.Name))
            {
                if (user.Profiles == null)
                {
                    user.Profiles = new HashedSet <UserProfile>();
                }
                addedProfile = user.Profiles.Add(_hapagProfiles[personGroup.Name]);
            }
            else if (_hapagModules.ContainsKey(personGroup.Name))
            {
                if (user.CustomRoles == null)
                {
                    user.CustomRoles = new HashedSet <UserCustomRole>();
                }
                var hapagModule = _hapagModules[personGroup.Name];
                Log.DebugFormat("adding customrole {0} to user {1} from group {2}", hapagModule.Name, user.Id,
                                personGroup.Name);
                addedRole = user.CustomRoles.Add(new UserCustomRole {
                    Role = hapagModule, UserId = user.Id
                });
            }
            return(addedProfile || addedRole);
        }
예제 #21
0
        public async Task <ActionResult> Registracija(HttpPostedFileBase file, string id)//
        {
            if (file != null && file.ContentLength > 0)
            {
                try
                {
                    string path = Path.Combine(Server.MapPath("~/Content/Users/"),
                                               (id + "." + file.ContentType.Split('/').Last()));
                    file.SaveAs(path);

                    byte[] fileR = System.IO.File.ReadAllBytes(path);

                    PersonGroup.dodajOsobuUGrupu(Convert.ToBase64String(fileR), id);
                    await Task.Run(() => RequestTraining.makeTrainRequest());
                }
                catch (Exception ex)
                {
                    ViewBag.Message = "ERROR:" + ex.Message.ToString();
                }
            }
            else
            {
                ViewBag.Message = "Please select file";
            }
            ViewBag.ID = id;
            return(RedirectToAction("Index", "Home"));
        }
예제 #22
0
        private async Task CheckGroup()
        {
            try
            {   //그룹이 이미 존재한다면 안 만들어도 된다.
                System.Diagnostics.Debug.WriteLine("그룹체크 시작");
                PersonGroup personGroup = await faceServiceClient.GetPersonGroupAsync(personGroupId);
            }
            //Catch and display Face API errors.
            catch (ClientException f)
            {
                System.Diagnostics.Debug.WriteLine("체크오류-그룹" + f);
                await CreatePersonGroup();

                System.Diagnostics.Debug.WriteLine("체크오류-트레이닝" + f);
                await TrainPersonGroup();
            }
            catch (FaceAPIException f)
            {
                System.Diagnostics.Debug.WriteLine("체크오류-그룹" + f);
                await CreatePersonGroup();

                System.Diagnostics.Debug.WriteLine("체크오류-트레이닝" + f);
                await TrainPersonGroup();
            }
        }
예제 #23
0
        private List <Schedule> FilterSchedulesForUser(List <Schedule> scheduleList, long userId)
        {
            List <Schedule> filteredScheduleList = new List <Schedule>();

            using (var uow = this.GetUnitOfWork())
            {
                foreach (Schedule s in scheduleList)
                {
                    var forPerson = uow.GetReadOnlyRepository <Person>().Get(s.ForPerson.Id);

                    if (forPerson is PersonGroup)
                    {
                        PersonGroup pg = (PersonGroup)forPerson;
                        foreach (User u in pg.Users)
                        {
                            if (u.Id == userId)
                            {
                                filteredScheduleList.Add(s);
                                break;
                            }
                        }
                    }
                    else if (forPerson is IndividualPerson)
                    {
                        IndividualPerson ip = (IndividualPerson)forPerson;
                        if (ip.Person.Id == userId)
                        {
                            filteredScheduleList.Add(s);
                            break;
                        }
                    }
                }
            }
            return(filteredScheduleList.Distinct().ToList());
        }
예제 #24
0
        /// <summary>
        /// Returns a query that shall be used to pick only the available costcenters
        /// </summary>
        /// <param name="subCustomer"></param>
        /// <param name="personId"></param>
        /// <returns></returns>
        private string BuildCostCentersFromMaximo(string subCustomer, string personId)
        {
            var groupNameToQuery = "'" + HapagPersonGroupConstants.BaseHapagLocationPrefix + subCustomer + "%" + "'";
            var results          =
                _maxDAO.FindByNativeQuery(
                    "select p.persongroup,description from PERSONGROUP p left join persongroupview v on p.PERSONGROUP = v.PERSONGROUP " +
                    "where (p.persongroup  like {0} ) and v.PERSONID = {1} and v.groupdefault = 1"
                    .Fmt(groupNameToQuery, "'" + personId + "'"));
            var list = results.Cast <IEnumerable <KeyValuePair <string, object> > >()
                       .Select(r => r.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase)).ToList();
            ISet <string> costcenters = new HashSet <string>();

            foreach (var groupsDescription in list)
            {
                var pg = new PersonGroup()
                {
                    Name        = groupsDescription["persongroup"] as string,
                    Description = groupsDescription["description"] as string,
                };
                var supergroup = HlagLocationUtil.IsSuperGroup(pg);
                if (HlagLocationUtil.IsALocationGroup(pg) && !supergroup)
                {
                    costcenters.Add(HlagLocationUtil.GetCostCenter(pg));
                }
            }
            if (!costcenters.Any())
            {
                return("1!=1");
            }


            var groupedLocation = new HlagGroupedLocation(subCustomer, costcenters, false);

            return(groupedLocation.CostCentersForQuery("glaccount"));
        }
예제 #25
0
    /// <summary>
    /// Gets the person group.
    /// </summary>
    /// <returns>The person group.</returns>
    /// <param name="groupId">Group ID.</param>
    public PersonGroup GetPersonGroup(string groupId)
    {
        if (string.IsNullOrEmpty(faceSubscriptionKey))
        {
            throw new Exception("The face-subscription key is not set.");
        }

        string requestUrl = string.Format("{0}/persongroups/{1}", GetFaceServiceUrl(), groupId);

        Dictionary <string, string> headers = new Dictionary <string, string>();

        headers.Add("ocp-apim-subscription-key", faceSubscriptionKey);

        HttpWebResponse response = CloudWebTools.DoWebRequest(requestUrl, "GET", "application/json", null, headers, true, false);

        PersonGroup group = null;

        if (!CloudWebTools.IsErrorStatus(response))
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());
            //group = JsonConvert.DeserializeObject<PersonGroup>(reader.ReadToEnd(), jsonSettings);
            group = JsonUtility.FromJson <PersonGroup>(reader.ReadToEnd());
        }
        else
        {
            ProcessFaceError(response);
        }

        return(group);
    }
예제 #26
0
 /// <summary>
 /// 根据<paramref name="searchText"/>过滤<see cref="Groups"/>
 /// </summary>
 /// <param name="searchText">查询关键字</param>
 public void GroupsFilter(string searchText)
 {
     PersonOnDisplay = Persons.FirstOrDefault();
     Groups.Clear();
     foreach (var person in Persons)
     {
         if (person.Name.Contains(searchText) ||
             person.StudentNumber.Contains(searchText) ||
             person.Dormitory.Contains(searchText) ||
             person.NativeProvince.Equals(searchText))
         {
             PersonGroup group = Groups.Where(g => g.LastName == person.LastName).FirstOrDefault();
             if (group == null)
             {
                 var newGroup = new PersonGroup(person.LastName);
                 newGroup.Items.Add(person);
                 Groups.Add(newGroup);
             }
             else
             {
                 group.Items.Add(person);
             }
         }
     }
 }
        private async void OnAddPersonGroupButtonClicked(object sender, RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(SettingsHelper.Instance.WorkspaceKey))
                {
                    throw new InvalidOperationException("Before you can create groups you need to define a Workspace Key in the Settings Page.");
                }

                Guid personGroupGuid = Guid.NewGuid();
                await FaceServiceHelper.CreatePersonGroupAsync(personGroupGuid.ToString(), this.personGroupNameTextBox.Text, SettingsHelper.Instance.WorkspaceKey);

                PersonGroup newGroup = new PersonGroup {
                    Name = this.personGroupNameTextBox.Text, PersonGroupId = personGroupGuid.ToString()
                };

                this.PersonGroups.Add(newGroup);
                this.personGroupsListView.SelectedValue = newGroup;

                this.personGroupNameTextBox.Text = "";
                this.addPersonGroupFlyout.Hide();

                this.needsTraining = true;
            }
            catch (Exception ex)
            {
                await Util.GenericApiCallExceptionHandler(ex, "Failure creating group");
            }
        }
        private List <PersonGroup> GetListByGroupId(string groupId, List <SysAddressBookMember> userInfos)
        {
            var allDeptList         = MailListApi.GetDepartmentList(GetToken()).department;
            var subDepts            = allDeptList.Where(a => a.parentid == Int32.Parse(groupId));
            List <PersonGroup> list = new List <PersonGroup>();



            foreach (var dept in subDepts)
            {
                PersonGroup person = new PersonGroup();
                person.WeixinId   = dept.id.ToString();
                person.WeixinName = dept.name;
                person.Type       = "Group";
                list.Add(person);
            }
            var members = userInfos.Where(a => a.Department.Replace("[", ",").Replace("]", ",").Contains("," + groupId + ",")).ToList();

            foreach (var member in members)
            {
                PersonGroup person = new PersonGroup();
                person.WeixinId   = member.UserId;
                person.WeixinName = member.UserName;
                person.Avatar     = member.Avatar;
                person.Type       = "Person";
                list.Add(person);
            }
            return(list);
        }
예제 #29
0
        private async Task UpdatePersonGroupList()
        {
            PersonGroup[] personGroups = Array.Empty <PersonGroup>();
            string        cogSrvcKey   = !string.IsNullOrWhiteSpace(txtCognitiveServicesAPIKey.Text) ? txtCognitiveServicesAPIKey.Text.Trim() : !string.IsNullOrWhiteSpace(_options.CSKey) ? _options.CSKey : string.Empty;
            string        cogSrvcEP    = !string.IsNullOrWhiteSpace(txtCognitiveServicesEndpoint.Text) ? txtCognitiveServicesEndpoint.Text.Trim() : !string.IsNullOrWhiteSpace(_options.CSEndpoint) ? _options.CSEndpoint : string.Empty;
            string        faceEndpoint = !string.IsNullOrWhiteSpace(txtCognitiveServicesEndpoint.Text) ? $"{txtCognitiveServicesEndpoint.Text.Trim()}face/v1.0" : !string.IsNullOrWhiteSpace(_options.FaceEndpoint) ? _options.FaceEndpoint : string.Empty;

            if (!string.IsNullOrWhiteSpace(cogSrvcKey) && !string.IsNullOrWhiteSpace(cogSrvcEP))
            {
                try
                {
                    _faceClient  = new FaceServiceClient(cogSrvcKey, faceEndpoint);
                    personGroups = await _faceClient.ListPersonGroupsAsync(cogSrvcKey);
                }
                catch
                {
                }
            }

            if (personGroups.Length > 0)
            {
                cmbPersonGroups.SelectedText = string.Empty;
                cmbPersonGroups.Items.Clear();
                cmbPersonGroups.Items.Add(string.Empty);
                for (int i = 0; i < personGroups.Length; i++)
                {
                    PersonGroup personGroup = personGroups[i];
                    cmbPersonGroups.Items.Add(personGroup.PersonGroupId);
                }
            }
        }
예제 #30
0
    // gets the person group info
    private void GetOrGreateUserGroup()
    {
        if (!string.IsNullOrEmpty(userGroupId) && faceManager != null)
        {
            try
            {
                personGroup = faceManager.GetPersonGroup(userGroupId);
            }
            catch (Exception ex)
            {
                Debug.Log(ex.Message);
                Debug.Log("Trying to create user-group '" + userGroupId + "'...");

                if (faceManager.CreatePersonGroup(userGroupId, userGroupId, string.Empty))
                {
                    faceManager.TrainPersonGroup(userGroupId);
                    personGroup = faceManager.GetPersonGroup(userGroupId);
                }

                Debug.Log("User-group '" + userGroupId + "' created.");
            }

            initedGroupId = (personGroup != null) ? personGroup.personGroupId : string.Empty;
        }
    }
예제 #31
0
 private static void SavePersonGroup(Person personToSave, int groupId)
 {
     var pg = new PersonGroup {GroupId = groupId, Created = DateTime.Now, Changed = DateTime.Now, Joined = DateTime.Now};
     personToSave.PersonGroups.Add(pg);
 }
예제 #32
0
        private static void GetPersonToSaveEntity(PersonViewModel person, Person currentPerson, oikonomosEntities context, out bool sendWelcomeEmail, out Church church, out Person personToSave)
        {
            sendWelcomeEmail = false;

            //We need some settings from the Church table
            church = (from c in context.Churches
                      where c.ChurchId == currentPerson.ChurchId
                      select c).FirstOrDefault();

            personToSave = new Person();
            if (person.PersonId != 0)
            {
                personToSave = FetchPerson(person.PersonId, context, currentPerson);
            }
            else
            {
                context.AddToPeople(personToSave);
                personToSave.ChurchId = church.ChurchId;
                personToSave.Church = church;

                personToSave.Created = DateTime.Now;
                if (church.SendWelcome)
                {
                    sendWelcomeEmail = true;
                }

                if (person.GroupId > 0)
                {
                    var pg = new PersonGroup
                                 {
                                     GroupId = person.GroupId,
                                     Person  = personToSave,
                                     Joined  = DateTime.Now,
                                     Created = DateTime.Now,
                                     Changed = DateTime.Now
                                 };
                    personToSave.PersonGroups.Add(pg);
                }
            }

            if (person.FamilyId == 0)
            {
                if (person.FindFamily)
                {
                    var family = (from f in context.Families
                                  join p in context.People
                                      on f.FamilyId equals p.FamilyId
                                  join g in context.PersonGroups
                                      on p.PersonId equals g.PersonId
                                  where f.FamilyName == person.Surname
                                      && g.GroupId == person.GroupId
                                  select f).FirstOrDefault();
                    if (family == null)
                    {
                        personToSave.Family = new Family();
                        personToSave.Family.Created = DateTime.Now;
                    }
                    else
                    {
                        personToSave.Family = family;
                    }
                }
                else
                {
                    personToSave.Family = new Family();
                    personToSave.Family.Created = DateTime.Now;
                }
            }
            else
            {
                personToSave.Family = (from f in context.Families
                                       where f.FamilyId == person.FamilyId
                                       select f).FirstOrDefault();

                if (personToSave.Family == null)
                {
                    personToSave.Family = new Family();
                    personToSave.Family.Created = DateTime.Now;
                }
            }

            personToSave.Firstname = person.Firstname;
            personToSave.Family.FamilyName = person.Surname;
            personToSave.Email = person.Email;
            personToSave.DateOfBirth = person.DateOfBirth_Value;
        }