Esempio n. 1
0
 public static List<PersonInfo> GetPersonInfoByBarcode(string Barcode)
 {
     List<PersonInfo> list2;
     try
     {
         Sql2KDataAccess access = new Sql2KDataAccess();
         List<PersonInfo> list = new List<PersonInfo>();
         DataSet set = access.Run_SqlText("select * from t_user where Barcode='" + Barcode + "'");
         if ((set != null) && (set.Tables[0].Rows.Count > 0))
         {
             for (int i = 0; i < set.Tables[0].Rows.Count; i++)
             {
                 PersonInfo item = new PersonInfo {
                     UserName = set.Tables[0].Rows[i]["UserName"].ToString(),
                     TrueName = set.Tables[0].Rows[i]["TrueName"].ToString(),
                     BarCode = set.Tables[0].Rows[i]["BarCode"].ToString()
                 };
                 list.Add(item);
             }
         }
         list2 = list;
     }
     catch (Exception exception)
     {
         throw exception;
     }
     return list2;
 }
Esempio n. 2
0
        public PersonalInfoDAL()
        {
            personalInfoModel = new PersonalInfoModel();
            _dataContext = new MDKDBMLDataContext();
            tPersonalInfoData = new TPersonalInfoData();
            personalInfoEntity = new PersonInfo();

            clients = new TClientInfo();
            clientModel = new ClientInfoModel();
        }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //Create a Person info object
        PersonInfo personInfo = new PersonInfo();

        personInfo.FirstName = tbxFirstName.Text;
        personInfo.LastName = tbxLastName.Text;

        person.Add(personInfo);
    }
Esempio n. 4
0
 public CheckInRecModel(int orgId, int? pid)
 {
     var q = from o in DbUtil.Db.Organizations
             where o.OrganizationId == orgId
             select o.OrganizationName;
     OrgName = q.SingleOrDefault();
     var q2 = from p in DbUtil.Db.People
              where p.PeopleId == pid
              select new PersonInfo
              {
                  PeopleId = p.PeopleId,
                  Name = p.Name,
                  Birthday = p.DOB,
                  ImageId = p.Picture.MediumId ?? 0,
                  Addr1 = p.PrimaryAddress,
                  Addr2 = p.PrimaryAddress2,
                  CityStateZip = p.CityStateZip,
                  Phone = p.HomePhone.FmtFone("H "),
                  Cell = p.CellPhone.FmtFone("C "),
                  Email = p.EmailAddress,
                  School = p.SchoolOther,
                  Year = p.Grade.ToString(),
                  CheckInNotes = p.CheckInNotes,
                  FamilyId = p.FamilyId
              };
     person = q2.SingleOrDefault();
     if (person == null)
         person = new PersonInfo
         {
             PeopleId = 0,
             Name = "not found",
         };
     else
     {
         var guid = (Guid?)(HttpContext.Current.Session["checkinguid"]);
         if (!guid.HasValue)
         {
             //var tt = new TemporaryToken
             //{
             //    Id = Guid.NewGuid(),
             //    CreatedBy = Util.UserId1,
             //    CreatedOn = Util.Now,
             //};
             //DbUtil.Db.TemporaryTokens.InsertOnSubmit(tt);
             //DbUtil.Db.SubmitChanges();
             //guid = tt.Id;
             HttpContext.Current.Session["checkinguid"] = guid;
         }
         this.guid = guid.ToString();
     }
     OrgId = orgId;
 }
Esempio n. 5
0
 public void DeletePersonOnlyName()
 {
     DataBase dataBase = new DataBase();
     string name = Guid.NewGuid().ToString();
     PersonInfo personInfo = new PersonInfo {Name = name};
     int rowsInserted = dataBase.PersonInfoInsert(personInfo);
     Assert.AreEqual(1, rowsInserted, "Person not inserted!");
     List<PersonInfo> list = dataBase.PersonInfoGetAll();
     Assert.IsNotNull(list, "At least one person info was expected!");
     PersonInfo info = list.Find(p => p.Name == name);
     Assert.AreEqual(name, info.Name, "PersonInfo not found! '{0}'", name);
     int rowsDeleted = dataBase.PersonInfoDelete(info.Id);
     Assert.AreEqual(1, rowsDeleted, "Person not deleted!");
 }
Esempio n. 6
0
 public void Generate(int uniqueNumber)
 {
     PersonInfo newPerson = new PersonInfo();
     newPerson.Age = uniqueNumber;
     if (uniqueNumber % 2 == 0)
     {
         newPerson.Name = "Ivan";
         newPerson.Gender = Gender.Male;
     }
     else
     {
         newPerson.Name = "Mariq";
         newPerson.Gender = Gender.Female;
     }
 }
Esempio n. 7
0
 public void OrderGetAll()
 {
     DataBase dataBase = new DataBase();
     string itemTypeName = Guid.NewGuid().ToString();
     ItemType itemType = new ItemType {Name = itemTypeName,};
     dataBase.ItemTypeInsert(itemType);
     ItemType itemTypeGet = dataBase.ItemTypeGet(itemTypeName);
     Assert.IsNotNull(itemTypeGet);
     string itemName = Guid.NewGuid().ToString();
     Item item = new Item
                 {
                     Name = itemName,
                     ItemTypeId = itemTypeGet.Id,
                 };
     dataBase.ItemInsert(item);
     Item itemGet = dataBase.ItemGet(itemName);
     Assert.IsNotNull(itemGet);
     string itemStatusName = Guid.NewGuid().ToString();
     ItemStatus itemStatus = new ItemStatus {Name = itemStatusName};
     dataBase.ItemStatusInsert(itemStatus);
     ItemStatus itemStatusGet = dataBase.ItemStatusGet(itemStatusName);
     Assert.IsNotNull(itemStatusGet);
     string personInfoName = Guid.NewGuid().ToString();
     string personInfoSurName = Guid.NewGuid().ToString();
     PersonInfo personInfo = new PersonInfo {Name = personInfoName, SurName = personInfoSurName,};
     dataBase.PersonInfoInsert(personInfo);
     PersonInfo personInfoGet = dataBase.PersonInfoGet(personInfoName, personInfoSurName);
     Assert.IsNotNull(personInfoGet);
     Order order = new Order
                   {
                       ItemId = itemGet.Id,
                       Count = 1,
                       ItemStatusId = itemStatusGet.Id,
                       LegalEntity = true,
                       PersonInfoId = personInfoGet.Id,
                       Postage = 0M.DecimalToString(),
                       Price = 1M.DecimalToString(),
                       BankId = -1,
                   };
     int rowsInserted = dataBase.OrderInsert(order);
     Assert.AreEqual(1, rowsInserted);
     List<Order> orders = dataBase.OrderGetAll();
     Assert.IsNotNull(orders);
     Order find = orders.Find(o => o.ItemId == itemGet.Id);
     Assert.IsNotNull(find);
 }
 public override void StoreWriterMatch(PersonInfo person)
 {
 }
Esempio n. 9
0
        private void ProcessMainInfo(MetadataResult <Series> seriesResult, SeriesResult seriesInfo, string preferredCountryCode, TmdbSettingsResult settings)
        {
            var series = seriesResult.Item;

            series.Name          = seriesInfo.Name;
            series.OriginalTitle = seriesInfo.Original_Name;
            series.SetProviderId(MetadataProviders.Tmdb, seriesInfo.Id.ToString(_usCulture));

            string voteAvg = seriesInfo.Vote_Average.ToString(CultureInfo.InvariantCulture);

            if (float.TryParse(voteAvg, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out float rating))
            {
                series.CommunityRating = rating;
            }

            series.Overview = seriesInfo.Overview;

            if (seriesInfo.Networks != null)
            {
                series.Studios = seriesInfo.Networks.Select(i => i.Name).ToArray();
            }

            if (seriesInfo.Genres != null)
            {
                series.Genres = seriesInfo.Genres.Select(i => i.Name).ToArray();
            }

            series.HomePageUrl = seriesInfo.Homepage;

            series.RunTimeTicks = seriesInfo.Episode_Run_Time.Select(i => TimeSpan.FromMinutes(i).Ticks).FirstOrDefault();

            if (string.Equals(seriesInfo.Status, "Ended", StringComparison.OrdinalIgnoreCase))
            {
                series.Status  = SeriesStatus.Ended;
                series.EndDate = seriesInfo.Last_Air_Date;
            }
            else
            {
                series.Status = SeriesStatus.Continuing;
            }

            series.PremiereDate = seriesInfo.First_Air_Date;

            var ids = seriesInfo.External_Ids;

            if (ids != null)
            {
                if (!string.IsNullOrWhiteSpace(ids.Imdb_Id))
                {
                    series.SetProviderId(MetadataProviders.Imdb, ids.Imdb_Id);
                }
                if (ids.Tvrage_Id > 0)
                {
                    series.SetProviderId(MetadataProviders.TvRage, ids.Tvrage_Id.ToString(_usCulture));
                }
                if (ids.Tvdb_Id > 0)
                {
                    series.SetProviderId(MetadataProviders.Tvdb, ids.Tvdb_Id.ToString(_usCulture));
                }
            }

            var contentRatings = (seriesInfo.Content_Ratings ?? new ContentRatings()).Results ?? new List <ContentRating>();

            var ourRelease     = contentRatings.FirstOrDefault(c => string.Equals(c.Iso_3166_1, preferredCountryCode, StringComparison.OrdinalIgnoreCase));
            var usRelease      = contentRatings.FirstOrDefault(c => string.Equals(c.Iso_3166_1, "US", StringComparison.OrdinalIgnoreCase));
            var minimumRelease = contentRatings.FirstOrDefault();

            if (ourRelease != null)
            {
                series.OfficialRating = ourRelease.Rating;
            }
            else if (usRelease != null)
            {
                series.OfficialRating = usRelease.Rating;
            }
            else if (minimumRelease != null)
            {
                series.OfficialRating = minimumRelease.Rating;
            }

            if (seriesInfo.Videos != null && seriesInfo.Videos.Results != null)
            {
                foreach (var video in seriesInfo.Videos.Results)
                {
                    if ((video.Type.Equals("trailer", StringComparison.OrdinalIgnoreCase) ||
                         video.Type.Equals("clip", StringComparison.OrdinalIgnoreCase)) &&
                        video.Site.Equals("youtube", StringComparison.OrdinalIgnoreCase))
                    {
                        series.AddTrailerUrl($"http://www.youtube.com/watch?v={video.Key}");
                    }
                }
            }

            seriesResult.ResetPeople();
            var tmdbImageUrl = settings.images.GetImageUrl("original");

            if (seriesInfo.Credits != null)
            {
                if (seriesInfo.Credits.Cast != null)
                {
                    foreach (var actor in seriesInfo.Credits.Cast.OrderBy(a => a.Order))
                    {
                        var personInfo = new PersonInfo
                        {
                            Name      = actor.Name.Trim(),
                            Role      = actor.Character,
                            Type      = PersonType.Actor,
                            SortOrder = actor.Order
                        };

                        if (!string.IsNullOrWhiteSpace(actor.Profile_Path))
                        {
                            personInfo.ImageUrl = tmdbImageUrl + actor.Profile_Path;
                        }

                        if (actor.Id > 0)
                        {
                            personInfo.SetProviderId(MetadataProviders.Tmdb, actor.Id.ToString(CultureInfo.InvariantCulture));
                        }

                        seriesResult.AddPerson(personInfo);
                    }
                }

                if (seriesInfo.Credits.Crew != null)
                {
                    var keepTypes = new[]
                    {
                        PersonType.Director,
                        PersonType.Writer,
                        PersonType.Producer
                    };

                    foreach (var person in seriesInfo.Credits.Crew)
                    {
                        // Normalize this
                        var type = TmdbUtils.MapCrewToPersonType(person);

                        if (!keepTypes.Contains(type, StringComparer.OrdinalIgnoreCase) &&
                            !keepTypes.Contains(person.Job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
                        {
                            continue;
                        }

                        seriesResult.AddPerson(new PersonInfo
                        {
                            Name = person.Name.Trim(),
                            Role = person.Job,
                            Type = type
                        });
                    }
                }
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Gets the persons from XML node.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <returns>IEnumerable{PersonInfo}.</returns>
        private IEnumerable <PersonInfo> GetPersonsFromXmlNode(XmlReader reader)
        {
            var name      = string.Empty;
            var type      = PersonType.Actor; // If type is not specified assume actor
            var role      = string.Empty;
            int?sortOrder = null;

            reader.MoveToContent();
            reader.Read();

            // Loop through each element
            while (!reader.EOF && reader.ReadState == ReadState.Interactive)
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.Name)
                    {
                    case "Name":
                        name = reader.ReadElementContentAsString() ?? string.Empty;
                        break;

                    case "Type":
                    {
                        var val = reader.ReadElementContentAsString();

                        if (!string.IsNullOrWhiteSpace(val))
                        {
                            type = val;
                        }
                        break;
                    }

                    case "Role":
                    {
                        var val = reader.ReadElementContentAsString();

                        if (!string.IsNullOrWhiteSpace(val))
                        {
                            role = val;
                        }
                        break;
                    }

                    case "SortOrder":
                    {
                        var val = reader.ReadElementContentAsString();

                        if (!string.IsNullOrWhiteSpace(val))
                        {
                            int intVal;
                            if (int.TryParse(val, NumberStyles.Integer, _usCulture, out intVal))
                            {
                                sortOrder = intVal;
                            }
                        }
                        break;
                    }

                    default:
                        reader.Skip();
                        break;
                    }
                }
                else
                {
                    reader.Read();
                }
            }

            var personInfo = new PersonInfo
            {
                Name      = name.Trim(),
                Role      = role,
                Type      = type,
                SortOrder = sortOrder
            };

            return(new[] { personInfo });
        }
Esempio n. 11
0
        // GET: Socials
        public ActionResult Index()
        {
            PersonInfo pi = SessionHelper.GetCurrentPersonInfo(db);

            return(View(db.Socials.Where(x => x.PersonInfo.Id == pi.Id).ToList()));
        }
Esempio n. 12
0
        private void ParseAdditionalMetadata <T>(MetadataResult <T> itemResult, RootObject result)
            where T : BaseItem
        {
            var item = itemResult.Item;

            var isConfiguredForEnglish = IsConfiguredForEnglish(item) || _configurationManager.Configuration.EnableNewOmdbSupport;

            // Grab series genres because IMDb data is better than TVDB. Leave movies alone
            // But only do it if English is the preferred language because this data will not be localized
            if (isConfiguredForEnglish && !string.IsNullOrWhiteSpace(result.Genre))
            {
                item.Genres = Array.Empty <string>();

                foreach (var genre in result.Genre
                         .Split(',', StringSplitOptions.RemoveEmptyEntries)
                         .Select(i => i.Trim())
                         .Where(i => !string.IsNullOrWhiteSpace(i)))
                {
                    item.AddGenre(genre);
                }
            }

            if (isConfiguredForEnglish)
            {
                // Omdb is currently English only, so for other languages skip this and let secondary providers fill it in
                item.Overview = result.Plot;
            }

            if (!Plugin.Instance.Configuration.CastAndCrew)
            {
                return;
            }

            if (!string.IsNullOrWhiteSpace(result.Director))
            {
                var person = new PersonInfo
                {
                    Name = result.Director.Trim(),
                    Type = PersonType.Director
                };

                itemResult.AddPerson(person);
            }

            if (!string.IsNullOrWhiteSpace(result.Writer))
            {
                var person = new PersonInfo
                {
                    Name = result.Writer.Trim(),
                    Type = PersonType.Writer
                };

                itemResult.AddPerson(person);
            }

            if (!string.IsNullOrWhiteSpace(result.Actors))
            {
                var actorList = result.Actors.Split(',');
                foreach (var actor in actorList)
                {
                    if (!string.IsNullOrWhiteSpace(actor))
                    {
                        var person = new PersonInfo
                        {
                            Name = actor.Trim(),
                            Type = PersonType.Actor
                        };

                        itemResult.AddPerson(person);
                    }
                }
            }
        }
Esempio n. 13
0
 public void UpdatePersonInfo()
 {
     DataBase dataBase = new DataBase();
     string name = Guid.NewGuid().ToString();
     PersonInfo personInfo = new PersonInfo
                             {
                                 Name = name,
                                 SurName = "surname",
                                 NickName = "nickname",
                                 Description = "description",
                                 Address = "adddress",
                                 PostNumber = 123,
                                 City = "city",
                                 Email = "*****@*****.**",
                                 Telephone = "00386 2 876 1234",
                                 TelephoneMobile = "++386 40 123 456",
                                 Fax = "+386 2 8761 211"
                             };
     int rowsInserted = dataBase.PersonInfoInsert(personInfo);
     Assert.AreEqual(1, rowsInserted, "Person not inserted!");
     List<PersonInfo> list = dataBase.PersonInfoGetAll();
     Assert.IsNotNull(list);
     PersonInfo find = list.Find(p => p.Name == name);
     Assert.IsNotNull(find);
     string newName = Guid.NewGuid().ToString();
     find.Name = newName;
     int rowsUpdated = dataBase.PersonInfoUpdate(find);
     Assert.AreEqual(1, rowsUpdated);
     PersonInfo updatedPersonInfo = dataBase.PersonInfoGet(find.Id);
     Assert.AreEqual(newName, updatedPersonInfo.Name);
     Assert.AreEqual(personInfo.SurName, updatedPersonInfo.SurName);
     Assert.AreEqual(personInfo.NickName, updatedPersonInfo.NickName);
     Assert.AreEqual(personInfo.Description, updatedPersonInfo.Description);
     Assert.AreEqual(personInfo.Address, updatedPersonInfo.Address);
     Assert.AreEqual(personInfo.PostNumber, updatedPersonInfo.PostNumber);
     Assert.AreEqual(personInfo.City, updatedPersonInfo.City);
     Assert.AreEqual(personInfo.Email, updatedPersonInfo.Email);
     Assert.AreEqual(personInfo.Telephone, updatedPersonInfo.Telephone);
     Assert.AreEqual(personInfo.TelephoneMobile, updatedPersonInfo.TelephoneMobile);
     Assert.AreEqual(personInfo.Fax, updatedPersonInfo.Fax);
 }
Esempio n. 14
0
        public override async Task <bool> UpdateFromOnlineMusicTrackAlbumPersonAsync(AlbumInfo albumInfo, PersonInfo person, string language, bool cacheOnly)
        {
            try
            {
                TrackArtist artistDetail = null;
                if (!string.IsNullOrEmpty(person.MusicBrainzId))
                {
                    artistDetail = await _musicBrainzHandler.GetArtistAsync(person.MusicBrainzId, cacheOnly).ConfigureAwait(false);
                }
                if (artistDetail == null)
                {
                    return(false);
                }

                person.Name        = artistDetail.Name;
                person.DateOfBirth = artistDetail.LifeSpan != null ? artistDetail.LifeSpan.Begin : null;
                person.DateOfDeath = artistDetail.LifeSpan != null ? artistDetail.LifeSpan.End : null;
                person.IsGroup     = string.IsNullOrEmpty(artistDetail.Type) ? false : artistDetail.Type.IndexOf("Group", StringComparison.InvariantCultureIgnoreCase) >= 0;
                person.Occupation  = PersonAspect.OCCUPATION_ARTIST;

                return(true);
            }
            catch (Exception ex)
            {
                ServiceRegistration.Get <ILogger>().Debug("MusicBrainzWrapper: Exception while processing person {0}", ex, person.ToString());
                return(false);
            }
        }
Esempio n. 15
0
 public override Task <bool> UpdateFromOnlineSeriesEpisodePersonAsync(EpisodeInfo episodeInfo, PersonInfo person, TvdbLanguage language, bool cacheOnly)
 {
     return(UpdateFromOnlineSeriesPersonAsync(episodeInfo.CloneBasicInstance <SeriesInfo>(), person, language, cacheOnly));
 }
Esempio n. 16
0
 public int Account_PersonInfo_Update(PersonInfo Person)
 {
     return accountbll.Account_PersonInfo_Update(Person);
 }
        /// <summary>
        /// 
        /// </summary>
        void RunStudentPersonalConsumer()
        {
            IStudentPersonalConsumer studentPersonalConsumer = new StudentPersonalConsumer("Sif3DemoApp");
            studentPersonalConsumer.Register();
            if (log.IsInfoEnabled) log.Info("Registered the Consumer.");

            try
            {
                // Retrieve Bart Simpson.
                Name name = new Name { FamilyName = "Simpson", GivenName = "Bart" };
                PersonInfo personInfo = new PersonInfo { Name = name };
                StudentPersonal studentPersonal = new StudentPersonal { PersonInfo = personInfo };
                ICollection<StudentPersonal> filteredStudents = studentPersonalConsumer.Retrieve(studentPersonal);

                foreach (StudentPersonal student in filteredStudents)
                {
                    if (log.IsInfoEnabled) log.Info("Filtered student name is " + student.PersonInfo.Name.GivenName + " " + student.PersonInfo.Name.FamilyName);
                }

                // Create and then retrieve a new student.
                Name newStudentName = new Name() { FamilyName = "Wayne", GivenName = "Bruce", Type = NameType.LGL };
                PersonInfo newStudentInfo = new PersonInfo() { Name = newStudentName };
                StudentPersonal newStudent = new StudentPersonal() { LocalId = "555", PersonInfo = newStudentInfo };
                Guid newStudentId = studentPersonalConsumer.Create(newStudent);
                if (log.IsInfoEnabled) log.Info("Created new student " + newStudent.PersonInfo.Name.GivenName + " " + newStudent.PersonInfo.Name.FamilyName);
                StudentPersonal retrievedNewStudent = studentPersonalConsumer.Retrieve(newStudentId);
                if (log.IsInfoEnabled) log.Info("Retrieved new student " + retrievedNewStudent.PersonInfo.Name.GivenName + " " + retrievedNewStudent.PersonInfo.Name.FamilyName);

                // Retrieve all students.
                ICollection<StudentPersonal> students = studentPersonalConsumer.Retrieve();

                foreach (StudentPersonal student in students)
                {
                    if (log.IsInfoEnabled) log.Info("Student name is " + student.PersonInfo.Name.GivenName + " " + student.PersonInfo.Name.FamilyName);
                }

                // Retrieve a single student.
                Guid studentId = students.ElementAt(1).Id;
                StudentPersonal secondStudent = studentPersonalConsumer.Retrieve(studentId);
                if (log.IsInfoEnabled) log.Info("Name of second student is " + secondStudent.PersonInfo.Name.GivenName + " " + secondStudent.PersonInfo.Name.FamilyName);

                // Update that student and confirm.
                secondStudent.PersonInfo.Name.GivenName = "Homer";
                secondStudent.PersonInfo.Name.FamilyName = "Simpson";
                studentPersonalConsumer.Update(secondStudent);
                secondStudent = studentPersonalConsumer.Retrieve(studentId);
                if (log.IsInfoEnabled) log.Info("Name of second student has been changed to " + secondStudent.PersonInfo.Name.GivenName + " " + secondStudent.PersonInfo.Name.FamilyName);

                // Delete that student and confirm.
                studentPersonalConsumer.Delete(studentId);
                students = studentPersonalConsumer.Retrieve();
                bool studentDeleted = true;

                foreach (StudentPersonal student in students)
                {

                    if (studentId == student.Id)
                    {
                        studentDeleted = false;
                        break;
                    }

                }

                if (studentDeleted)
                {
                    if (log.IsInfoEnabled) log.Info("Student " + secondStudent.PersonInfo.Name.GivenName + " " + secondStudent.PersonInfo.Name.FamilyName + " was successfully deleted.");
                }
                else
                {
                    if (log.IsInfoEnabled) log.Info("Student " + secondStudent.PersonInfo.Name.GivenName + " " + secondStudent.PersonInfo.Name.FamilyName + " was NOT deleted.");
                }

            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                studentPersonalConsumer.Unregister();
                if (log.IsInfoEnabled) log.Info("Unregistered the Consumer.");
            }
        }
Esempio n. 18
0
        public TPersonalInfoData createBusinessPerson(List<PersonalInfoModel> list)
        {
            try
            {
                var entityList = new List<PersonInfo>();

                list.ForEach(item =>
                {
                    var model = new PersonInfo();

                    model.FirstName = item.FirstName;
                    model.MiddleName = item.MiddleName;
                    model.LastName = item.LastName;
                    model.ContactNo = item.ContactNo;
                    model.AlternateNo = item.AlternateNo;
                    model.EmailID = item.EmailID;
                    model.DateOfBirth = item.DateOfBirth;
                    model.Address = item.Address;
                    model.BPAN = item.BPAN;

                    entityList.Add(model);
                });

                _dataContext.PersonInfos.InsertAllOnSubmit(entityList);
                _dataContext.SubmitChanges();

                tPersonalInfoData.SuccessCode = SuccessCodes.RECORD_SAVED_SUCCESSFULLY;
                tPersonalInfoData.SuccessMessage = SuccessMessages.RECORD_SAVED_SUCCESSFULLY_MSG;

                return tPersonalInfoData;

            }

            catch (Exception exp)
            {
                tPersonalInfoData.ErrorCode = ErrorCodes.DATA_ACCESS_ERROR;
                tPersonalInfoData.ErrorMessage = exp.Message;
                return tPersonalInfoData;
            }


        }
Esempio n. 19
0
        public async Task <MetadataResult <Movie> > Update(int[] siteNum, string[] sceneID, CancellationToken cancellationToken)
        {
            var result = new MetadataResult <Movie>()
            {
                Item   = new Movie(),
                People = new List <PersonInfo>(),
            };

            if (sceneID == null)
            {
                return(result);
            }

            var sceneURL = Helper.Decode(sceneID[0]);

            if (!sceneURL.StartsWith("http", StringComparison.OrdinalIgnoreCase))
            {
                sceneURL = Helper.GetSearchBaseURL(siteNum) + sceneURL;
            }

            var sceneData = await HTML.ElementFromURL(sceneURL, cancellationToken).ConfigureAwait(false);

            result.Item.ExternalId = sceneURL;

            result.Item.Name     = sceneData.SelectSingleText("//h1[@class='no-space transform-none']");
            result.Item.Overview = sceneData.SelectSingleText("//meta[@name='description']/@content");
            result.Item.AddStudio("Porndoe Premium");

            var dateNode = sceneData.SelectSingleText("//div[@class='h5 h5-published nowrap color-rgba255-06']");

            if (DateTime.TryParseExact(dateNode.Split("•").Last().Trim(), "MMM dd, yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out var sceneDateObj))
            {
                result.Item.PremiereDate = sceneDateObj;
            }

            var genres = sceneData.SelectNodesSafe("//a[@class='inline-links']");

            foreach (var genreLink in genres)
            {
                var genreName = genreLink.InnerText;

                result.Item.AddGenre(genreName);
            }

            var actorsNode = sceneData.SelectNodesSafe("//span[@class='group inline']/a");

            foreach (var actorLink in actorsNode)
            {
                var actorPageURL = actorLink.Attributes["href"].Value;
                var actorDate    = await HTML.ElementFromURL(actorPageURL, cancellationToken).ConfigureAwait(false);

                var actorName = actorDate.SelectSingleText("//div[@data-item='c-13 r-11 m-c-15 / middle']/h1");
                var res       = new PersonInfo
                {
                    Name = actorName,
                };

                var actorPhoto = actorDate.SelectSingleText("//div[@class='avatar']/picture[2]/img/@data-src");
                if (!string.IsNullOrEmpty(actorPhoto))
                {
                    if (!actorPhoto.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                    {
                        actorPhoto = Helper.GetSearchBaseURL(siteNum) + actorPhoto;
                    }

                    res.ImageUrl = actorPhoto;
                }

                result.People.Add(res);
            }

            return(result);
        }
Esempio n. 20
0
        /// <summary>
        /// Processes the main info.
        /// </summary>
        /// <param name="resultItem">The result item.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="preferredCountryCode">The preferred country code.</param>
        /// <param name="movieData">The movie data.</param>
        private void ProcessMainInfo(MetadataResult <T> resultItem, TmdbSettingsResult settings, string preferredCountryCode, MovieDbProvider.CompleteMovieData movieData)
        {
            var movie = resultItem.Item;

            movie.Name = movieData.GetTitle() ?? movie.Name;

            movie.OriginalTitle = movieData.GetOriginalTitle();

            // Bug in Mono: WebUtility.HtmlDecode should return null if the string is null but in Mono it generate an System.ArgumentNullException.
            movie.Overview = movieData.overview != null?WebUtility.HtmlDecode(movieData.overview) : null;

            movie.Overview = movie.Overview != null?movie.Overview.Replace("\n\n", "\n") : null;

            movie.HomePageUrl = movieData.homepage;

            var hasBudget = movie as IHasBudget;

            if (hasBudget != null)
            {
                hasBudget.Budget  = movieData.budget;
                hasBudget.Revenue = movieData.revenue;
            }

            if (!string.IsNullOrEmpty(movieData.tagline))
            {
                movie.Tagline = movieData.tagline;
            }

            if (movieData.production_countries != null)
            {
                movie.ProductionLocations = movieData
                                            .production_countries
                                            .Select(i => i.name)
                                            .ToList();
            }

            movie.SetProviderId(MetadataProviders.Tmdb, movieData.id.ToString(_usCulture));
            movie.SetProviderId(MetadataProviders.Imdb, movieData.imdb_id);

            if (movieData.belongs_to_collection != null)
            {
                movie.SetProviderId(MetadataProviders.TmdbCollection,
                                    movieData.belongs_to_collection.id.ToString(CultureInfo.InvariantCulture));

                var movieItem = movie as Movie;

                if (movieItem != null)
                {
                    movieItem.CollectionName = movieData.belongs_to_collection.name;
                }
            }

            float  rating;
            string voteAvg = movieData.vote_average.ToString(CultureInfo.InvariantCulture);

            if (float.TryParse(voteAvg, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out rating))
            {
                movie.CommunityRating = rating;
            }

            movie.VoteCount = movieData.vote_count;

            //release date and certification are retrieved based on configured country and we fall back on US if not there and to minimun release date if still no match
            if (movieData.releases != null && movieData.releases.countries != null)
            {
                var releases = movieData.releases.countries.Where(i => !string.IsNullOrWhiteSpace(i.certification)).ToList();

                var ourRelease = releases.FirstOrDefault(c => string.Equals(c.iso_3166_1, preferredCountryCode, StringComparison.OrdinalIgnoreCase));
                var usRelease  = releases.FirstOrDefault(c => string.Equals(c.iso_3166_1, "US", StringComparison.OrdinalIgnoreCase));

                if (ourRelease != null)
                {
                    var ratingPrefix = string.Equals(preferredCountryCode, "us", StringComparison.OrdinalIgnoreCase) ? "" : preferredCountryCode + "-";
                    var newRating    = ratingPrefix + ourRelease.certification;

                    newRating = newRating.Replace("de-", "FSK-", StringComparison.OrdinalIgnoreCase);

                    movie.OfficialRating = newRating;
                }
                else if (usRelease != null)
                {
                    movie.OfficialRating = usRelease.certification;
                }
            }

            if (!string.IsNullOrWhiteSpace(movieData.release_date))
            {
                DateTime r;

                // These dates are always in this exact format
                if (DateTime.TryParse(movieData.release_date, _usCulture, DateTimeStyles.None, out r))
                {
                    movie.PremiereDate   = r.ToUniversalTime();
                    movie.ProductionYear = movie.PremiereDate.Value.Year;
                }
            }

            //studios
            if (movieData.production_companies != null)
            {
                movie.Studios.Clear();

                foreach (var studio in movieData.production_companies.Select(c => c.name))
                {
                    movie.AddStudio(studio);
                }
            }

            // genres
            // Movies get this from imdb
            var genres = movieData.genres ?? new List <MovieDbProvider.GenreItem>();

            foreach (var genre in genres.Select(g => g.name))
            {
                movie.AddGenre(genre);
            }

            resultItem.ResetPeople();
            var tmdbImageUrl = settings.images.secure_base_url + "original";

            //Actors, Directors, Writers - all in People
            //actors come from cast
            if (movieData.casts != null && movieData.casts.cast != null)
            {
                foreach (var actor in movieData.casts.cast.OrderBy(a => a.order))
                {
                    var personInfo = new PersonInfo
                    {
                        Name      = actor.name.Trim(),
                        Role      = actor.character,
                        Type      = PersonType.Actor,
                        SortOrder = actor.order
                    };

                    if (!string.IsNullOrWhiteSpace(actor.profile_path))
                    {
                        personInfo.ImageUrl = tmdbImageUrl + actor.profile_path;
                    }

                    if (actor.id > 0)
                    {
                        personInfo.SetProviderId(MetadataProviders.Tmdb, actor.id.ToString(CultureInfo.InvariantCulture));
                    }

                    resultItem.AddPerson(personInfo);
                }
            }

            //and the rest from crew
            if (movieData.casts != null && movieData.casts.crew != null)
            {
                foreach (var person in movieData.casts.crew)
                {
                    // Normalize this
                    var type = person.department;
                    if (string.Equals(type, "writing", StringComparison.OrdinalIgnoreCase))
                    {
                        type = PersonType.Writer;
                    }

                    var personInfo = new PersonInfo
                    {
                        Name = person.name.Trim(),
                        Role = person.job,
                        Type = type
                    };

                    if (!string.IsNullOrWhiteSpace(person.profile_path))
                    {
                        personInfo.ImageUrl = tmdbImageUrl + person.profile_path;
                    }

                    if (person.id > 0)
                    {
                        personInfo.SetProviderId(MetadataProviders.Tmdb, person.id.ToString(CultureInfo.InvariantCulture));
                    }

                    resultItem.AddPerson(personInfo);
                }
            }

            if (movieData.keywords != null && movieData.keywords.keywords != null)
            {
                movie.Keywords = movieData.keywords.keywords.Select(i => i.name).ToList();
            }

            if (movieData.trailers != null && movieData.trailers.youtube != null &&
                movieData.trailers.youtube.Count > 0)
            {
                var hasTrailers = movie as IHasTrailers;
                if (hasTrailers != null)
                {
                    hasTrailers.RemoteTrailers = movieData.trailers.youtube.Select(i => new MediaUrl
                    {
                        Url  = string.Format("https://www.youtube.com/watch?v={0}", i.source),
                        Name = i.name
                    }).ToList();
                }
            }
        }
Esempio n. 21
0
        protected async Task <ApiWrapperImageCollection <TvdbBanner> > GetActorFanArtAsync(PersonInfo person, TvdbLanguage language)
        {
            if (person == null || person.TvdbId < 1)
            {
                return(null);
            }
            int seriesTvdbId;

            if (!_seriesToActorMap.GetMappedId(person.TvdbId.ToString(), out string seriesId) || !int.TryParse(seriesId, out seriesTvdbId))
            {
                return(null);
            }
            TvdbSeries seriesDetail = await _tvdbHandler.GetSeriesAsync(seriesTvdbId, language, false, true, true).ConfigureAwait(false);

            if (seriesDetail == null)
            {
                return(null);
            }
            TvdbActor actor = seriesDetail.TvdbActors.FirstOrDefault(a => a.Id == person.TvdbId);

            if (actor == null)
            {
                return(null);
            }
            ApiWrapperImageCollection <TvdbBanner> images = new ApiWrapperImageCollection <TvdbBanner>();

            images.Id = actor.Id.ToString();
            images.Thumbnails.AddRange(new TvdbBanner[] { actor.ActorImage });
            return(images);
        }
Esempio n. 22
0
        public async Task <MetadataResult <Movie> > Update(int[] siteNum, string[] sceneID, CancellationToken cancellationToken)
        {
            var result = new MetadataResult <Movie>()
            {
                Item   = new Movie(),
                People = new List <PersonInfo>(),
            };

            if (sceneID == null)
            {
                return(result);
            }

            var instanceToken = await GetToken(siteNum, cancellationToken).ConfigureAwait(false);

            if (string.IsNullOrEmpty(instanceToken))
            {
                return(result);
            }

            var url       = $"{Helper.GetSearchSearchURL(siteNum)}/v2/releases?type={sceneID[1]}&id={sceneID[0]}";
            var sceneData = await GetDataFromAPI(url, instanceToken, cancellationToken).ConfigureAwait(false);

            if (sceneData == null)
            {
                return(result);
            }

            sceneData = (JObject)sceneData["result"].First;
            if (sceneData == null)
            {
                return(result);
            }

            string domain       = new Uri(Helper.GetSearchBaseURL(siteNum)).Host,
                   sceneTypeURL = sceneID[1];

            if (sceneTypeURL.Equals("scene", StringComparison.OrdinalIgnoreCase))
            {
                switch (domain)
                {
                case "www.brazzers.com":
                    sceneTypeURL = "video";
                    break;
                }
            }

            var sceneURL = Helper.GetSearchBaseURL(siteNum) + $"/{sceneTypeURL}/{sceneID[0]}/";

            result.Item.ExternalId = sceneURL;

            result.Item.Name     = (string)sceneData["title"];
            result.Item.Overview = (string)sceneData["description"];
            result.Item.AddStudio((string)sceneData["brand"]);

            var sceneDateObj = (DateTime)sceneData["dateReleased"];

            result.Item.PremiereDate = sceneDateObj;

            foreach (var genreLink in sceneData["tags"])
            {
                var genreName = (string)genreLink["name"];

                result.Item.AddGenre(genreName);
            }

            foreach (var actorLink in sceneData["actors"])
            {
                var actorPageURL = $"{Helper.GetSearchSearchURL(siteNum)}/v1/actors?id={actorLink["id"]}";
                var actorData    = await GetDataFromAPI(actorPageURL, instanceToken, cancellationToken).ConfigureAwait(false);

                if (actorData != null)
                {
                    actorData = (JObject)actorData["result"].First;

                    var actor = new PersonInfo
                    {
                        Name = (string)actorLink["name"],
                    };

                    if (actorData["images"] != null && actorData["images"].Type == JTokenType.Object)
                    {
                        actor.ImageUrl = (string)actorData["images"]["profile"].First["xs"]["url"];
                    }

                    result.People.Add(actor);
                }
            }

            return(result);
        }
 /// <summary>
 /// Constructor that accepts values for all mandatory fields
 /// </summary>
 ///<param name="refId">The ID (GUID) that uniquely identifies the instance of the object.</param>
 ///<param name="personInfo">A PersonInfo</param>
 ///
 public StudentContactPersonal(string refId, PersonInfo personInfo) : base(Adk.SifVersion, StudentDTD.STUDENTCONTACTPERSONAL)
 {
     this.RefId      = refId;
     this.PersonInfo = personInfo;
 }
Esempio n. 24
0
 private void SetPersonControlInfo(PersonInfo personInfo)
 {
     this.tbPersonCode.Text = personInfo.PersonCode;
     this.tbPersonName.Text = personInfo.PersonName;
     this.ddlPersonType.SelectedValue = ((Int32)personInfo.PersonType).ToString();
     this.tbEntryDate.Text = personInfo.EntryDate.ToString("yyyy-MM-dd").Equals("0001-01-01") ? "" : personInfo.EntryDate.ToString("yyyy-MM-dd");
     this.tbLeftDate.Text = personInfo.LeftDate.ToString("yyyy-MM-dd").Equals("0001-01-01") ? "" : personInfo.LeftDate.ToString("yyyy-MM-dd");
     this.ddlDepartment.SelectedValue = personInfo.DepartmentID;
     this.ddlProject.SelectedValue = personInfo.ProjectID;
     this.BaseGridViewDataBind(this.gvCommonList, CommonFeeType.CommonSalary);
     this.BaseGridViewDataBind(this.gvPositionList, CommonFeeType.Position);
     this.BaseGridViewDataBind(this.gvFloatList, CommonFeeType.Float);
     this.BaseGridViewDataBind(this.gvCooperateList, CommonFeeType.Cooperate);
     this.BaseGridViewDataBind(this.gvVirtualList, CommonFeeType.Virtual);
     this.BaseGridViewDataBind(this.gvServiceList, CommonFeeType.Service);
     if (this.action != ActionType.Add)
     {
         //this.gvDepartProjectGridViewDataBind(false);
         switch (personInfo.PersonType)
         {
             case PersonType.LaoWu:
                 this.liCommon.Visible = false;
                 this.liPosition.Visible = false;
                 this.liFloat.Visible = false;
                 this.liCooperate.Visible = false;
                 this.liVirtual.Visible = false;
                 this.tabs2.Visible = false;
                 this.tabs3.Visible = false;
                 this.tabs4.Visible = false;
                 this.tabs5.Visible = false;
                 this.tabs6.Visible = false;
                 break;
             case PersonType.JianZhi:
                 this.liCommon.Visible = false;
                 this.liFloat.Visible = false;
                 this.liCooperate.Visible = false;
                 this.liVirtual.Visible = false;
                 this.liService.Visible = false;
                 this.tabs2.Visible = false;
                 this.tabs4.Visible = false;
                 this.tabs5.Visible = false;
                 this.tabs6.Visible = false;
                 this.tabs7.Visible = false;
                 break;
             case PersonType.Retire:
                 this.liCommon.Visible = false;
                 this.liFloat.Visible = false;
                 this.liCooperate.Visible = false;
                 this.liVirtual.Visible = false;
                 this.liService.Visible = false;
                 this.tabs2.Visible = false;
                 this.tabs4.Visible = false;
                 this.tabs5.Visible = false;
                 this.tabs6.Visible = false;
                 this.tabs7.Visible = false;
                 break;
             case PersonType.QuanZhi:
                 this.liService.Visible = false;
                 this.tabs7.Visible = false;
                 break;
             case PersonType.WaiPin:
                 this.liService.Visible = false;
                 this.tabs7.Visible = false;
                 break;
             case PersonType.PaiChu:
                 this.liCooperate.Visible = false;
                 this.liVirtual.Visible = false;
                 this.liFloat.Visible = false;
                 this.liService.Visible = false;
                 this.tabs4.Visible = false;
                 this.tabs5.Visible = false;
                 this.tabs6.Visible = false;
                 this.tabs7.Visible = false;
                 break;
             case PersonType.Soldier:
                 this.liService.Visible = false;
                 this.tabs7.Visible = false;
                 break;
         }
     }
     this.tbPersonCode.Enabled = String.IsNullOrEmpty(personInfo.ParentID);
     this.tbPersonName.Enabled = String.IsNullOrEmpty(personInfo.ParentID);
 }
        /// <inheritdoc />
        public async Task <MetadataResult <Series> > GetMetadata(SeriesInfo info, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogDebug("[GetMetadata] Starting for {name}", info.Name);
                var tvMazeClient = new TvMazeClient(_httpClientFactory.CreateClient(NamedClient.Default));
                var result       = new MetadataResult <Series>();

                var  tvMazeId   = TvHelpers.GetTvMazeId(info.ProviderIds);
                Show?tvMazeShow = null;
                if (tvMazeId.HasValue)
                {
                    // Search by tv maze id.
                    tvMazeShow = await tvMazeClient.Shows.GetShowMainInformation(tvMazeId.Value).ConfigureAwait(false);
                }

                if (tvMazeShow == null &&
                    info.ProviderIds.TryGetValue(MetadataProvider.Imdb.ToString(), out var imdbId) &&
                    !string.IsNullOrEmpty(imdbId))
                {
                    // Lookup by imdb id.
                    tvMazeShow = await tvMazeClient.Lookup.GetShowByImdbId(imdbId).ConfigureAwait(false);
                }

                if (tvMazeShow == null &&
                    info.ProviderIds.TryGetValue(MetadataProvider.TvRage.ToString(), out var tvRageId) &&
                    !string.IsNullOrEmpty(tvRageId))
                {
                    // Lookup by tv rage id.
                    var id = Convert.ToInt32(tvRageId, CultureInfo.InvariantCulture);
                    tvMazeShow = await tvMazeClient.Lookup.GetShowByTvRageId(id).ConfigureAwait(false);
                }

                if (tvMazeShow == null &&
                    info.ProviderIds.TryGetValue(MetadataProvider.Tvdb.ToString(), out var tvdbId) &&
                    !string.IsNullOrEmpty(tvdbId))
                {
                    var id = Convert.ToInt32(tvdbId, CultureInfo.InvariantCulture);
                    tvMazeShow = await tvMazeClient.Lookup.GetShowByTheTvdbId(id).ConfigureAwait(false);
                }

                if (tvMazeShow == null)
                {
                    // Series still not found, search by name.
                    var parsedName = _libraryManager.ParseName(info.Name);
                    _logger.LogDebug("[GetMetadata] No TV Maze Id, searching by parsed name: {@name}", parsedName);
                    tvMazeShow = await GetIdentifyShow(parsedName, tvMazeClient).ConfigureAwait(false);
                }

                if (tvMazeShow == null)
                {
                    // Invalid tv maze id.
                    _logger.LogDebug("[GetMetadata] No TV Maze result found for {name}", info.Name);
                    return(result);
                }

                var series = new Series();
                series.Name   = tvMazeShow.Name;
                series.Genres = tvMazeShow.Genres.ToArray();

                if (!string.IsNullOrWhiteSpace(tvMazeShow.Network?.Name))
                {
                    var networkName = tvMazeShow.Network.Name;
                    if (!string.IsNullOrWhiteSpace(tvMazeShow.Network?.Country?.Code))
                    {
                        networkName = $"{tvMazeShow.Network.Name} ({tvMazeShow.Network.Country.Code})";
                    }

                    series.Studios = new[] { networkName };
                }

                if (DateTime.TryParse(tvMazeShow.Premiered, out var premiereDate))
                {
                    series.PremiereDate   = premiereDate;
                    series.ProductionYear = premiereDate.Year;
                }

                if (tvMazeShow.Rating?.Average != null)
                {
                    series.CommunityRating = (float?)tvMazeShow.Rating.Average;
                }

                if (tvMazeShow.Runtime.HasValue)
                {
                    series.RunTimeTicks = TimeSpan.FromMinutes(tvMazeShow.Runtime.Value).Ticks;
                }

                if (string.Equals(tvMazeShow.Status, "Running", StringComparison.OrdinalIgnoreCase))
                {
                    series.Status = SeriesStatus.Continuing;
                }
                else if (string.Equals(tvMazeShow.Status, "Ended", StringComparison.OrdinalIgnoreCase))
                {
                    series.Status = SeriesStatus.Ended;
                }

                series.Overview    = TvHelpers.GetStrippedHtml(tvMazeShow.Summary);
                series.HomePageUrl = tvMazeShow.Url;
                SetProviderIds(tvMazeShow, series);

                // Set cast.
                var castMembers = await tvMazeClient.Shows.GetShowCastAsync(tvMazeShow.Id).ConfigureAwait(false);

                foreach (var castMember in castMembers)
                {
                    var personInfo = new PersonInfo();
                    personInfo.SetProviderId(TvMazePlugin.ProviderId, castMember.Person.Id.ToString(CultureInfo.InvariantCulture));
                    personInfo.Name     = castMember.Person.Name;
                    personInfo.Role     = castMember.Character.Name;
                    personInfo.Type     = PersonType.Actor;
                    personInfo.ImageUrl = castMember.Person.Image?.Original
                                          ?? castMember.Person.Image?.Medium;

                    result.AddPerson(personInfo);
                }

                result.Item        = series;
                result.HasMetadata = true;

                _logger.LogDebug("[GetMetadata] Metadata result: {@series}", tvMazeShow);
                return(result);
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "[GetMetadata]");
                return(new MetadataResult <Series>());
            }
        }
Esempio n. 26
0
        public async Task <MetadataResult <Movie> > GetMetadata(MovieInfo info, CancellationToken cancellationToken)
        {
            var tmdbId = info.GetProviderId(MetadataProvider.Tmdb);
            var imdbId = info.GetProviderId(MetadataProvider.Imdb);

            if (string.IsNullOrEmpty(tmdbId) && string.IsNullOrEmpty(imdbId))
            {
                // ParseName is required here.
                // Caller provides the filename with extension stripped and NOT the parsed filename
                var parsedName    = _libraryManager.ParseName(info.Name);
                var cleanedName   = TmdbUtils.CleanName(parsedName.Name);
                var searchResults = await _tmdbClientManager.SearchMovieAsync(cleanedName, info.Year ?? parsedName.Year ?? 0, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);

                if (searchResults.Count > 0)
                {
                    tmdbId = searchResults[0].Id.ToString(CultureInfo.InvariantCulture);
                }
            }

            if (string.IsNullOrEmpty(tmdbId) && !string.IsNullOrEmpty(imdbId))
            {
                var movieResultFromImdbId = await _tmdbClientManager.FindByExternalIdAsync(imdbId, FindExternalSource.Imdb, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);

                if (movieResultFromImdbId?.MovieResults.Count > 0)
                {
                    tmdbId = movieResultFromImdbId.MovieResults[0].Id.ToString();
                }
            }

            if (string.IsNullOrEmpty(tmdbId))
            {
                return(new MetadataResult <Movie>());
            }

            var movieResult = await _tmdbClientManager
                              .GetMovieAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken)
                              .ConfigureAwait(false);

            if (movieResult == null)
            {
                return(new MetadataResult <Movie>());
            }

            var movie = new Movie
            {
                Name                = movieResult.Title ?? movieResult.OriginalTitle,
                OriginalTitle       = movieResult.OriginalTitle,
                Overview            = movieResult.Overview?.Replace("\n\n", "\n", StringComparison.InvariantCulture),
                Tagline             = movieResult.Tagline,
                ProductionLocations = movieResult.ProductionCountries.Select(pc => pc.Name).ToArray()
            };
            var metadataResult = new MetadataResult <Movie>
            {
                HasMetadata    = true,
                ResultLanguage = info.MetadataLanguage,
                Item           = movie
            };

            movie.SetProviderId(MetadataProvider.Tmdb, tmdbId);
            movie.SetProviderId(MetadataProvider.Imdb, movieResult.ImdbId);
            if (movieResult.BelongsToCollection != null)
            {
                movie.SetProviderId(MetadataProvider.TmdbCollection, movieResult.BelongsToCollection.Id.ToString(CultureInfo.InvariantCulture));
                movie.CollectionName = movieResult.BelongsToCollection.Name;
            }

            movie.CommunityRating = Convert.ToSingle(movieResult.VoteAverage);

            if (movieResult.Releases?.Countries != null)
            {
                var releases = movieResult.Releases.Countries.Where(i => !string.IsNullOrWhiteSpace(i.Certification)).ToList();

                var ourRelease = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, info.MetadataCountryCode, StringComparison.OrdinalIgnoreCase));
                var usRelease  = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, "US", StringComparison.OrdinalIgnoreCase));

                if (ourRelease != null)
                {
                    var ratingPrefix = string.Equals(info.MetadataCountryCode, "us", StringComparison.OrdinalIgnoreCase) ? string.Empty : info.MetadataCountryCode + "-";
                    var newRating    = ratingPrefix + ourRelease.Certification;

                    newRating = newRating.Replace("de-", "FSK-", StringComparison.OrdinalIgnoreCase);

                    movie.OfficialRating = newRating;
                }
                else if (usRelease != null)
                {
                    movie.OfficialRating = usRelease.Certification;
                }
            }

            movie.PremiereDate   = movieResult.ReleaseDate;
            movie.ProductionYear = movieResult.ReleaseDate?.Year;

            if (movieResult.ProductionCompanies != null)
            {
                movie.SetStudios(movieResult.ProductionCompanies.Select(c => c.Name));
            }

            var genres = movieResult.Genres;

            foreach (var genre in genres.Select(g => g.Name))
            {
                movie.AddGenre(genre);
            }

            if (movieResult.Keywords?.Keywords != null)
            {
                for (var i = 0; i < movieResult.Keywords.Keywords.Count; i++)
                {
                    movie.AddTag(movieResult.Keywords.Keywords[i].Name);
                }
            }

            if (movieResult.Credits?.Cast != null)
            {
                // TODO configurable
                foreach (var actor in movieResult.Credits.Cast.OrderBy(a => a.Order).Take(TmdbUtils.MaxCastMembers))
                {
                    var personInfo = new PersonInfo
                    {
                        Name      = actor.Name.Trim(),
                        Role      = actor.Character,
                        Type      = PersonType.Actor,
                        SortOrder = actor.Order
                    };

                    if (!string.IsNullOrWhiteSpace(actor.ProfilePath))
                    {
                        personInfo.ImageUrl = _tmdbClientManager.GetProfileUrl(actor.ProfilePath);
                    }

                    if (actor.Id > 0)
                    {
                        personInfo.SetProviderId(MetadataProvider.Tmdb, actor.Id.ToString(CultureInfo.InvariantCulture));
                    }

                    metadataResult.AddPerson(personInfo);
                }
            }

            if (movieResult.Credits?.Crew != null)
            {
                var keepTypes = new[]
                {
                    PersonType.Director,
                    PersonType.Writer,
                    PersonType.Producer
                };

                foreach (var person in movieResult.Credits.Crew)
                {
                    // Normalize this
                    var type = TmdbUtils.MapCrewToPersonType(person);

                    if (!keepTypes.Contains(type, StringComparer.OrdinalIgnoreCase) &&
                        !keepTypes.Contains(person.Job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    var personInfo = new PersonInfo
                    {
                        Name = person.Name.Trim(),
                        Role = person.Job,
                        Type = type
                    };

                    if (!string.IsNullOrWhiteSpace(person.ProfilePath))
                    {
                        personInfo.ImageUrl = _tmdbClientManager.GetPosterUrl(person.ProfilePath);
                    }

                    if (person.Id > 0)
                    {
                        personInfo.SetProviderId(MetadataProvider.Tmdb, person.Id.ToString(CultureInfo.InvariantCulture));
                    }

                    metadataResult.AddPerson(personInfo);
                }
            }

            if (movieResult.Videos?.Results != null)
            {
                var trailers = new List <MediaUrl>();
                for (var i = 0; i < movieResult.Videos.Results.Count; i++)
                {
                    var video = movieResult.Videos.Results[0];
                    if (!TmdbUtils.IsTrailerType(video))
                    {
                        continue;
                    }

                    trailers.Add(new MediaUrl
                    {
                        Url  = string.Format(CultureInfo.InvariantCulture, "https://www.youtube.com/watch?v={0}", video.Key),
                        Name = video.Name
                    });
                }

                movie.RemoteTrailers = trailers;
            }

            return(metadataResult);
        }
        public async Task <MetadataResult <Movie> > Update(int[] siteNum, string[] sceneID, CancellationToken cancellationToken)
        {
            var result = new MetadataResult <Movie>()
            {
                Item   = new Movie(),
                People = new List <PersonInfo>(),
            };

            if (sceneID == null)
            {
                return(result);
            }

            var sceneURL = Helper.Decode(sceneID[0]);

            if (!sceneURL.StartsWith("http", StringComparison.OrdinalIgnoreCase))
            {
                sceneURL = Helper.GetSearchBaseURL(siteNum) + sceneURL;
            }

            var sceneData = await HTML.ElementFromURL(sceneURL, cancellationToken).ConfigureAwait(false);

            result.Item.ExternalId = sceneURL;

            var javID = sceneData.SelectSingleText("//div[@id='video_id']//td[@class='text']");
            var title = sceneData.SelectSingleText("//div[@id='video_title']//h3");

            if (!string.IsNullOrEmpty(javID))
            {
                result.Item.OriginalTitle = javID.ToUpperInvariant();
                title = title.Replace(javID, string.Empty, StringComparison.OrdinalIgnoreCase);
            }

            result.Item.Name = title;

            var studio = sceneData.SelectSingleText("//div[@id='video_maker']//td[@class='text']");

            if (!string.IsNullOrEmpty(studio))
            {
                result.Item.AddStudio(studio);
            }

            var date = sceneData.SelectSingleText("//div[@id='video_date']//td[@class='text']");

            if (DateTime.TryParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var sceneDateObj))
            {
                result.Item.PremiereDate = sceneDateObj;
            }

            var genreNode = sceneData.SelectNodesSafe("//div[@id='video_genres']//td[@class='text']//a");

            foreach (var genreLink in genreNode)
            {
                var genreName = genreLink.InnerText;

                result.Item.AddGenre(genreName);
            }

            var actorsNode = sceneData.SelectNodesSafe("//div[@id='video_cast']//td[@class='text']//span[@class='cast']//a");

            foreach (var actorLink in actorsNode)
            {
                var actorName = actorLink.InnerText;

                if (actorName != "----")
                {
                    switch (Plugin.Instance.Configuration.JAVActorNamingStyle)
                    {
                    case JAVActorNamingStyle.WesternStyle:
                        actorName = string.Join(" ", actorName.Split().Reverse());
                        break;
                    }

                    var actor = new PersonInfo
                    {
                        Name = actorName,
                    };

                    result.People.Add(actor);
                }
            }

            return(result);
        }
Esempio n. 28
0
 public void Skip()
 {
     PersonInfo.FinishTutorial();
     FlyOut();
 }
        public async Task <MetadataResult <Movie> > Update(int[] siteNum, string[] sceneID, CancellationToken cancellationToken)
        {
            var result = new MetadataResult <Movie>()
            {
                Item   = new Movie(),
                People = new List <PersonInfo>(),
            };

            if (sceneID == null)
            {
                return(result);
            }

            var sceneURL  = Helper.Decode(sceneID[0]);
            var sceneData = await HTML.ElementFromURL(sceneURL, cancellationToken).ConfigureAwait(false);

            result.Item.ExternalId = sceneURL;

            var javID = sceneData.SelectSingleText("//dt[text()='DVD ID:']/following-sibling::dd[1]");

            if (javID.StartsWith("--", StringComparison.OrdinalIgnoreCase))
            {
                javID = sceneData.SelectSingleText("//dt[text()='Content ID:']/following-sibling::dd[1]");
            }

            if (javID.Contains(" ", StringComparison.OrdinalIgnoreCase))
            {
                javID = javID.Replace(" ", "-", StringComparison.OrdinalIgnoreCase);
            }

            result.Item.OriginalTitle = javID.ToUpperInvariant();
            result.Item.Name          = Decensor(sceneData.SelectSingleText("//cite[@itemprop='name']"));
            result.Item.Overview      = Decensor(sceneData.SelectSingleText("//div[@class='cmn-box-description01']").Replace("Product Description", string.Empty, StringComparison.OrdinalIgnoreCase));

            result.Item.AddStudio(sceneData.SelectSingleText("//dd[@itemprop='productionCompany']"));

            var date = sceneData.SelectSingleText("//dd[@itemprop='dateCreated']");

            if (!string.IsNullOrEmpty(date))
            {
                date = date
                       .Replace(".", string.Empty, StringComparison.OrdinalIgnoreCase)
                       .Replace(",", string.Empty, StringComparison.OrdinalIgnoreCase)
                       .Replace("Sept", "Sep", StringComparison.OrdinalIgnoreCase)
                       .Replace("June", "Jun", StringComparison.OrdinalIgnoreCase)
                       .Replace("July", "Jul", StringComparison.OrdinalIgnoreCase)
                       .Trim();

                if (DateTime.TryParseExact(date, "MMM dd yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out var sceneDateObj))
                {
                    result.Item.PremiereDate = sceneDateObj;
                }
            }

            var genreNode = sceneData.SelectNodesSafe("//a[@itemprop='genre']");

            foreach (var genreLink in genreNode)
            {
                var genreName = genreLink.InnerText;
                genreName = Decensor(genreName);

                result.Item.AddGenre(genreName);
            }

            var actorsNode = sceneData.SelectNodesSafe("//div[@itemprop='actors']//span[@itemprop='name']");

            foreach (var actorLink in actorsNode)
            {
                var actorName = actorLink.InnerText;

                if (actorName != "----")
                {
                    if (Plugin.Instance.Configuration.JAVActorNamingStyle == JAVActorNamingStyle.JapaneseStyle)
                    {
                        actorName = string.Join(" ", actorName.Split().Reverse());
                    }

                    var actor = new PersonInfo
                    {
                        Name = actorName,
                    };

                    var photoXpath = string.Format(CultureInfo.InvariantCulture, "//div[@id='{0}']//img[contains(@alt, '{1}')]/@src", actorName.Replace(" ", string.Empty, StringComparison.OrdinalIgnoreCase), actorName);
                    var actorPhoto = sceneData.SelectSingleText(photoXpath);

                    if (!actorPhoto.Contains("nowprinting.gif", StringComparison.OrdinalIgnoreCase))
                    {
                        actor.ImageUrl = actorPhoto;
                    }

                    result.People.Add(actor);
                }
            }

            return(result);
        }
Esempio n. 30
0
        public async Task <MetadataResult <BaseItem> > Update(int[] siteNum, string[] sceneID, CancellationToken cancellationToken)
        {
            var result = new MetadataResult <BaseItem>()
            {
                Item   = new Movie(),
                People = new List <PersonInfo>(),
            };

            if (sceneID == null)
            {
                return(result);
            }

            var sceneURL = Helper.Decode(sceneID[0]);

            if (!sceneURL.StartsWith("http", StringComparison.OrdinalIgnoreCase))
            {
                sceneURL = Helper.GetSearchBaseURL(siteNum) + sceneURL;
            }

            var sceneData = await HTML.ElementFromURL(sceneURL, cancellationToken).ConfigureAwait(false);

            result.Item.ExternalId = sceneURL;

            result.Item.Name = sceneData.SelectSingleText("//h1").Trim().Split("\n").First();

            foreach (var movieInfo in sceneData.SelectNodesSafe("//table[@class='movieInfo']//tr"))
            {
                var cellNode = movieInfo.SelectNodesSafe("./td");
                switch (cellNode[0].InnerText)
                {
                case "Released":
                    var date = cellNode[1].InnerText.Trim();
                    if (DateTime.TryParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var sceneDateObj))
                    {
                        result.Item.PremiereDate = sceneDateObj;
                    }

                    break;

                case "Sex Styles":
                    var genreNode = cellNode[1].SelectNodesSafe(".//a[contains(@href, 'category')]");
                    foreach (var genreLink in genreNode)
                    {
                        var genreName = genreLink.InnerText;

                        result.Item.AddGenre(genreName);
                    }

                    break;

                case "Actress(es)":
                    var actorsNode = cellNode[1].SelectNodesSafe(".//a[contains(@href, 'actor')]");
                    foreach (var actorLink in actorsNode)
                    {
                        var actorName = actorLink.InnerText;

                        switch (Plugin.Instance.Configuration.JAVActorNamingStyle)
                        {
                        case JAVActorNamingStyle.JapaneseStyle:
                            actorName = string.Join(" ", actorName.Split().Reverse());

                            break;
                        }

                        var actor = new PersonInfo
                        {
                            Name = actorName,
                        };

                        result.People.Add(actor);
                    }

                    break;
                }
            }

            return(result);
        }
Esempio n. 31
0
        internal static async Task <GetAuthorizedPeopleResult> GetAuthorizedPeopleAsync(
            IHealthVaultConnection connection,
            Guid personIdCursor,
            Instant?authCreatedSinceDate,
            int numResults)
        {
            if (numResults < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(numResults), Resources.GetAuthorizedPeopleNumResultsNegative);
            }

            StringBuilder     parameters = new StringBuilder(256);
            XmlWriterSettings settings   = SDKHelper.XmlUnicodeWriterSettings;

            settings.OmitXmlDeclaration = true;
            settings.ConformanceLevel   = ConformanceLevel.Fragment;

            using (XmlWriter writer = XmlWriter.Create(parameters, settings))
            {
                writer.WriteStartElement("parameters");

                if (personIdCursor != Guid.Empty)
                {
                    writer.WriteElementString("person-id-cursor", personIdCursor.ToString());
                }

                if (authCreatedSinceDate != null)
                {
                    writer.WriteElementString(
                        "authorizations-created-since",
                        SDKHelper.XmlFromInstant(authCreatedSinceDate.Value));
                }

                if (numResults != 0)
                {
                    writer.WriteElementString("num-results", numResults.ToString(CultureInfo.InvariantCulture));
                }

                writer.WriteEndElement(); // parameters
                writer.Flush();
            }

            HealthServiceResponseData responseData = await connection.ExecuteAsync(HealthVaultMethods.GetAuthorizedPeople, 1, parameters.ToString()).ConfigureAwait(false);

            Collection <PersonInfo> personInfos = new Collection <PersonInfo>();

            XPathExpression navExp =
                SDKHelper.GetInfoXPathExpressionForMethod(
                    responseData.InfoNavigator, "GetAuthorizedPeople");
            XPathNavigator infoNav = responseData.InfoNavigator.SelectSingleNode(navExp);
            XPathNavigator nav     = infoNav.SelectSingleNode("response-results/person-info");

            if (nav != null)
            {
                do
                {
                    PersonInfo personInfo = PersonInfo.CreateFromXml(nav);
                    personInfos.Add(personInfo);
                }while (nav.MoveToNext("person-info", string.Empty));

                nav.MoveToNext();
            }
            else
            {
                nav = infoNav.SelectSingleNode("response-results/more-results");
            }

            return(new GetAuthorizedPeopleResult(personInfos, nav.ValueAsBoolean));
        }
 public override void StoreDirectorMatch(PersonInfo person)
 {
 }
Esempio n. 33
0
 public CommandsAndCodeBehindViewModel(PersonInfo personInfo)
 {
     PersonInfo = personInfo ?? throw new ArgumentNullException(nameof(personInfo));
     UpdateFullInformationCommand = new RelayCommand(UpdateFullInformation, UpdateFullInformationCanExecute);
 }
        public async Task <MetadataResult <Movie> > Update(int[] siteNum, string[] sceneID, CancellationToken cancellationToken)
        {
            var result = new MetadataResult <Movie>()
            {
                Item   = new Movie(),
                People = new List <PersonInfo>(),
            };

            if (sceneID == null)
            {
                return(result);
            }

            string sceneURL  = Helper.Decode(sceneID[0]),
                   sceneDate = sceneID[1];

            if (!sceneURL.StartsWith("http", StringComparison.OrdinalIgnoreCase))
            {
                sceneURL = Helper.GetSearchBaseURL(siteNum) + sceneURL;
            }

            var sceneData = await HTML.ElementFromURL(sceneURL, cancellationToken).ConfigureAwait(false);

            result.Item.ExternalId = sceneURL;

            result.Item.Name     = sceneData.SelectSingleText("//span[@class='title_bar_hilite']");
            result.Item.Overview = sceneData.SelectSingleText("//span[@class='update_description']");
            result.Item.AddStudio("Jules Jordan");

            if (!string.IsNullOrEmpty(sceneDate))
            {
                if (DateTime.TryParseExact(sceneDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var sceneDateObj))
                {
                    result.Item.PremiereDate = sceneDateObj;
                }
            }

            var genreNode = sceneData.SelectNodesSafe("//span[@class='update_tags']/a");

            foreach (var genreLink in genreNode)
            {
                var genreName = genreLink.InnerText;

                result.Item.AddGenre(genreName);
            }

            var actorsNode = sceneData.SelectNodesSafe("//div[@class='gallery_info']/*[1]//span[@class='update_models']//a");

            foreach (var actorLink in actorsNode)
            {
                var actor = new PersonInfo
                {
                    Name = actorLink.InnerText,
                };

                var actorPage = await HTML.ElementFromURL(actorLink.Attributes["href"].Value, cancellationToken).ConfigureAwait(false);

                var actorPhotoNode = actorPage.SelectSingleNode("//img[contains(@class, 'model_bio_thumb')]");
                if (actorPhotoNode != null)
                {
                    string actorPhoto;
                    if (actorPhotoNode.Attributes.Contains("src0_3x"))
                    {
                        actorPhoto = actorPhotoNode.Attributes["src0_3x"].Value;
                    }
                    else
                    {
                        actorPhoto = actorPhotoNode.Attributes["src0"].Value;
                    }

                    if (!actorPhoto.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                    {
                        actorPhoto = Helper.GetSearchBaseURL(siteNum) + actorPhoto;
                    }

                    actor.ImageUrl = actorPhoto;
                }

                result.People.Add(actor);
            }

            return(result);
        }
Esempio n. 35
0
 public IEnumerable <PersonInfo> Post([FromBody] PersonInfo p)
 {
     return(_repository.Add(p));
 }
Esempio n. 36
0
        /// <summary>
        /// Read the contents of the .opf file and update the book entity
        /// </summary>
        /// <param name="bookResult">The book result.</param>
        /// <param name="metaFile">The meta file.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        private void ReadOpfData(MetadataResult <Book> bookResult, string metaFile, CancellationToken cancellationToken)
        {
            var book = bookResult.Item;

            cancellationToken.ThrowIfCancellationRequested();

            var doc = new XmlDocument();

            doc.Load(metaFile);

            var namespaceManager = new XmlNamespaceManager(doc.NameTable);

            namespaceManager.AddNamespace("dc", DcNamespace);
            namespaceManager.AddNamespace("opf", OpfNamespace);

            var nameNode = doc.SelectSingleNode("//dc:title", namespaceManager);

            if (nameNode != null)
            {
                book.Name = nameNode.InnerText;
            }

            var overViewNode = doc.SelectSingleNode("//dc:description", namespaceManager);

            if (overViewNode != null)
            {
                book.Overview = overViewNode.InnerText;
            }


            var studioNode = doc.SelectSingleNode("//dc:publisher", namespaceManager);

            if (studioNode != null)
            {
                book.AddStudio(studioNode.InnerText);
            }

            var isbnNode = doc.SelectSingleNode("//dc:identifier[@opf:scheme='ISBN']", namespaceManager);

            if (isbnNode != null)
            {
                book.SetProviderId("ISBN", isbnNode.InnerText);
            }

            var amazonNode = doc.SelectSingleNode("//dc:identifier[@opf:scheme='AMAZON']", namespaceManager);

            if (amazonNode != null)
            {
                book.SetProviderId("AMAZON", amazonNode.InnerText);
            }

            var genresNodes = doc.SelectNodes("//dc:subject", namespaceManager);

            if (genresNodes != null && genresNodes.Count > 0)
            {
                foreach (var node in genresNodes.Cast <XmlNode>().Where(node => !book.Tags.Contains(node.InnerText)))
                {
                    // Adding to tags because we can't be sure the values are all genres
                    book.Genres.Add(node.InnerText);
                }
            }

            var authorNode = doc.SelectSingleNode("//dc:creator", namespaceManager);

            if (authorNode != null)
            {
                var person = new PersonInfo {
                    Name = authorNode.InnerText, Type = "Author"
                };

                bookResult.People.Add(person);
            }

            var seriesIndexNode = doc.SelectSingleNode("//opf:meta[@name='calibre:series_index']", namespaceManager);

            if (seriesIndexNode != null && seriesIndexNode.Attributes != null)
            {
                try
                {
                    book.IndexNumber = Convert.ToInt32(seriesIndexNode.Attributes["content"].Value);
                }
                catch (Exception e)
                {
                    _logger.ErrorException("Error parsing Calibre series index", e);
                }
            }

            var seriesNameNode = doc.SelectSingleNode("//opf:meta[@name='calibre:series']", namespaceManager);

            if (seriesNameNode != null && seriesNameNode.Attributes != null)
            {
                try
                {
                    book.SeriesName = seriesNameNode.Attributes["content"].Value;
                }
                catch (Exception e)
                {
                    _logger.ErrorException("Error parsing Calibre series name", e);
                }
            }

            var ratingNode = doc.SelectSingleNode("//opf:meta[@name='calibre:rating']", namespaceManager);

            if (ratingNode != null && ratingNode.Attributes != null)
            {
                try
                {
                    book.CommunityRating = Convert.ToInt32(ratingNode.Attributes["content"].Value);
                }
                catch (Exception e)
                {
                    _logger.ErrorException("Error parsing Calibre rating node", e);
                }
            }
        }
Esempio n. 37
0
 public IEnumerable <PersonInfo> Put(int id, [FromBody] PersonInfo p)
 {
     return(_repository.Update(id, p));
 }
Esempio n. 38
0
 private bool IsPersonType(PersonInfo person, string type)
 => string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase) ||
 string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase);
Esempio n. 39
0
 private PersonInfo GetInfoFromPageControl()
 {
     PersonInfo info = null;
     switch (action)
     {
         case ActionType.Add:
             info = new PersonInfo();//orderno做主键
             info.PersonID = CommonTools.Instance.GetMaxOrderNo(PersonInfoDBConst.TableName, PersonInfoDBConst.PersonID).ToString();
             info.ParentID = this.parentID;
             break;
         case ActionType.Edit:
             info = PersonInfoAdapter.Instance.LoadPersonInfo(personID);
             break;
     }
     info.PersonCode = this.tbPersonCode.Text.Trim();
     info.PersonName = this.tbPersonName.Text.Trim();
     info.PersonType = EnumHelper.Parse<PersonType>(this.ddlPersonType.SelectedValue);
     string str = this.tbEntryDate.Text.Trim();
     info.EntryDate = str.Length > 0 ? DateTime.Parse(str) : DateTime.Parse("0001-01-01");
     str = this.tbLeftDate.Text.Trim();
     info.LeftDate = str.Length > 0 ? DateTime.Parse(str) : DateTime.Parse("0001-01-01");
     info.Dimission = str.Length > 0;
     if (this.ddlDepartment.SelectedIndex > 0)
     {
         info.DepartmentID = this.ddlDepartment.SelectedValue;
         String nm = this.ddlDepartment.SelectedItem.Text.Replace(" ", "").Trim();
         info.DepartmentName = nm.StartsWith("-") ? nm.Substring(1).Trim() : nm;
     }
     if (this.ddlProject.SelectedIndex > 0)
     {
         info.ProjectID = this.ddlProject.SelectedValue;
         String nm = this.ddlProject.SelectedItem.Text.Replace(" ", "").Trim();
         info.ProjectName = nm.StartsWith("-") ? nm.Substring(1).Trim() : nm;
     }
     else
     {
         info.ProjectID = "";
         info.ProjectName = "";
     }
     return info;
 }
Esempio n. 40
0
 public override Task <bool> UpdateFromOnlineMusicTrackPersonAsync(TrackInfo trackInfo, PersonInfo person, string language, bool cacheOnly)
 {
     return(UpdateFromOnlineMusicTrackAlbumPersonAsync(trackInfo.CloneBasicInstance <AlbumInfo>(), person, language, cacheOnly));
 }
Esempio n. 41
0
 public override bool UpdateFromOnlineSeriesEpisodePerson(EpisodeInfo episodeInfo, PersonInfo person, string language, bool cacheOnly)
 {
     return(UpdateFromOnlineSeriesPerson(episodeInfo.CloneBasicInstance <SeriesInfo>(), person, language, cacheOnly));
 }
Esempio n. 42
0
 public void InsertPersonAll()
 {
     DataBase dataBase = new DataBase();
     string name = Guid.NewGuid().ToString();
     PersonInfo personInfo = new PersonInfo
                             {
                                 Name = name,
                                 SurName = "surname",
                                 NickName = "nickname",
                                 Description = "description",
                                 Address = "adddress",
                                 PostNumber = 123,
                                 City = "city",
                                 Email = "*****@*****.**",
                                 Telephone = "00386 2 876 1234",
                                 TelephoneMobile = "++386 40 123 456",
                                 Fax = "+386 2 8761 211"
                             };
     int rowsInserted = dataBase.PersonInfoInsert(personInfo);
     Assert.AreEqual(1, rowsInserted, "Person not inserted!");
 }
Esempio n. 43
0
        public override bool GetFanArt <T>(T infoObject, string language, string fanartMediaType, out ApiWrapperImageCollection <TvMazeImageCollection> images)
        {
            images = new ApiWrapperImageCollection <TvMazeImageCollection>();

            try
            {
                if (fanartMediaType == FanArtMediaTypes.Series)
                {
                    EpisodeInfo episode = infoObject as EpisodeInfo;
                    SeasonInfo  season  = infoObject as SeasonInfo;
                    SeriesInfo  series  = infoObject as SeriesInfo;
                    if (series == null && season != null)
                    {
                        series = season.CloneBasicInstance <SeriesInfo>();
                    }
                    if (series == null && episode != null)
                    {
                        series = episode.CloneBasicInstance <SeriesInfo>();
                    }
                    if (series != null && series.TvMazeId > 0)
                    {
                        // Download all image information, filter later!
                        TvMazeSeries seriesDetail = _tvMazeHandler.GetSeries(series.TvMazeId, false);
                        if (seriesDetail != null)
                        {
                            images.Id = series.TvMazeId.ToString();
                            images.Posters.Add(seriesDetail.Images);
                            return(true);
                        }
                    }
                }
                else if (fanartMediaType == FanArtMediaTypes.Episode)
                {
                    EpisodeInfo episode = infoObject as EpisodeInfo;
                    if (episode != null && episode.SeriesTvMazeId > 0 && episode.SeasonNumber.HasValue && episode.EpisodeNumbers.Count > 0)
                    {
                        // Download all image information, filter later!
                        TvMazeEpisode episodeDetail = _tvMazeHandler.GetSeriesEpisode(episode.SeriesTvMazeId, episode.SeasonNumber.Value, episode.FirstEpisodeNumber, false);
                        if (episodeDetail != null)
                        {
                            images.Id = episode.SeriesTvMazeId.ToString();
                            images.Thumbnails.Add(episodeDetail.Images);
                            return(true);
                        }
                    }
                }
                else if (fanartMediaType == FanArtMediaTypes.Actor)
                {
                    PersonInfo person = infoObject as PersonInfo;
                    if (person != null && person.TvMazeId > 0)
                    {
                        // Download all image information, filter later!
                        TvMazePerson personDetail = _tvMazeHandler.GetPerson(person.TvMazeId, false);
                        if (personDetail != null)
                        {
                            images.Id = person.TvMazeId.ToString();
                            images.Thumbnails.Add(personDetail.Images);
                            return(true);
                        }
                    }
                }
                else if (fanartMediaType == FanArtMediaTypes.Character)
                {
                    CharacterInfo character = infoObject as CharacterInfo;
                    if (character != null && character.TvMazeId > 0)
                    {
                        // Download all image information, filter later!
                        TvMazePerson personDetail = _tvMazeHandler.GetCharacter(character.TvMazeId, false);
                        if (personDetail != null)
                        {
                            images.Id = character.TvMazeId.ToString();
                            images.Thumbnails.Add(personDetail.Images);
                            return(true);
                        }
                    }
                }
                else
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                ServiceRegistration.Get <ILogger>().Debug(GetType().Name + ": Exception downloading images", ex);
            }
            return(false);
        }
        public async Task <MetadataResult <Movie> > GetMetadata(MovieInfo info, CancellationToken cancellationToken)
        {
            var           metadataResult = new MetadataResult <Movie>();
            JavVideoIndex index          = null;

            _logger?.Info($"{Name}-{nameof(GetMetadata)} info:{_jsonSerializer.SerializeToString(info)}");

            if ((index = info.GetJavVideoIndex(_jsonSerializer)) == null)
            {
                var res = await GetSearchResults(info, cancellationToken).ConfigureAwait(false);

                if (res.Count() == 0 || (index = res.FirstOrDefault().GetJavVideoIndex(_jsonSerializer)) == null)
                {
                    _logger?.Info($"{Name}-{nameof(GetMetadata)} name:{info.Name} not found 0.");
                    return(metadataResult);
                }
            }

            if (index == null)
            {
                _logger?.Info($"{Name}-{nameof(GetMetadata)} name:{info.Name} not found 1.");
                return(metadataResult);
            }

            var sc = scrapers.FirstOrDefault(o => o.Name == index.Provider);

            if (sc == null)
            {
                return(metadataResult);
            }

            var m = await sc.Get(index);

            if (m == null)
            {
                _logger?.Info($"{Name}-{nameof(GetMetadata)} name:{info.Name} not found 2.");
                return(metadataResult);
            }

            _logger?.Info($"{Name}-{nameof(GetMetadata)} name:{info.Name} {_jsonSerializer.SerializeToString(m)}");

            metadataResult.HasMetadata = true;
            metadataResult.QueriedById = true;

            //忽略部分类别
            if (m.Genres?.Any() == true)
            {
                m.Genres.RemoveAll(o => Plugin.Instance?.Configuration?.IsIgnoreGenre(o) == true);
                if (Plugin.Instance?.Configuration?.GenreIgnoreActor == true && m.Actors?.Any() == true)
                {
                    m.Genres.RemoveAll(o => m.Actors.Contains(o));
                }
            }

            metadataResult.Item = new Movie
            {
                Name           = $"{m.Num} {m.Title}",
                Overview       = m.Plot,
                ProductionYear = m.GetYear(),
                OriginalTitle  = m.Title,
                Genres         = m.Genres?.ToArray() ?? new string[] { },
                CollectionName = m.Set,
                SortName       = m.Num,
                ExternalId     = m.Num,
            };

            metadataResult.Item.SetJavVideoIndex(_jsonSerializer, index);

            var dt = m.GetDate();

            if (dt != null)
            {
                metadataResult.Item.PremiereDate = metadataResult.Item.DateCreated = dt.Value;
            }

            if (!string.IsNullOrWhiteSpace(m.Studio))
            {
                metadataResult.Item.AddStudio(m.Studio);
            }

            if (!string.IsNullOrWhiteSpace(m.Director))
            {
                var pi = new PersonInfo
                {
                    Name = m.Director,
                    Type = PersonType.Director,
                };
                metadataResult.AddPerson(pi);
            }

            if (m.Actors?.Any() == true)
            {
                foreach (var cast in m.Actors)
                {
                    var pi = new PersonInfo
                    {
                        Name = cast,
                        Type = PersonType.Actor,
                    };
                    metadataResult.AddPerson(pi);
                }
            }

            try
            {
                var cachePath = Path.Combine(_appPaths.CachePath, Name, m.Provider, $"{m.Num}.json");
                Directory.CreateDirectory(Path.GetDirectoryName(cachePath));
                _jsonSerializer.SerializeToFile(m, cachePath);
            }
            catch
            {
            }

            return(metadataResult);
        }
        /// <summary>
        /// Binds the attendees grid.
        /// </summary>
        private void BindAttendeesGrid( bool isExporting = false )
        {
            // Get Group Type filter
            var groupTypes = this.GetSelectedGroupTypes();
            if ( groupTypes == null || !groupTypes.Any() )
            {
                return;
            }
            var groupTypeIdList = groupTypes.Select( t => t.Id ).ToList();

            // Get the daterange filter
            var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues( drpSlidingDateRange.DelimitedValues );
            if ( dateRange.End == null )
            {
                dateRange.End = RockDateTime.Now;
            }
            var start = dateRange.Start;
            var end = dateRange.End;

            // Get the group filter
            var groupIdList = new List<int>();
            string groupIds = GetSelectedGroupIds().AsDelimited( "," );
            if ( !string.IsNullOrWhiteSpace( groupIds ) )
            {
                groupIdList = groupIds.Split( ',' ).AsIntegerList();
            }

            // If campuses were included, filter attendances by those that have selected campuses
            // if 'null' is one of the campuses, treat that as a 'CampusId is Null'
            var includeNullCampus = clbCampuses.SelectedValues.Any( a => a.Equals( "null", StringComparison.OrdinalIgnoreCase ) );
            var campusIdList = clbCampuses.SelectedValues.AsIntegerList();
            campusIdList.Remove( 0 ); // remove 0 from the list, just in case it is there
            if ( !includeNullCampus && !campusIdList.Any() )
            {
                campusIdList = null;
            }

            // If schedules were included, filter attendance by those that have the selected schedules
            var scheduleIdList = spSchedules.SelectedValues.AsIntegerList();
            scheduleIdList.Remove( 0 );
            if ( !scheduleIdList.Any() )
            {
                scheduleIdList = null;
            }

            // we want to get the first 2 visits at a minimum so we can show the dates in the grid
            int nthVisitsTake = 2;
            int? byNthVisit = null;
            if ( radByVisit.Checked )
            {
                // If we are filtering by nth visit, we might want to get up to first 5
                byNthVisit = ddlNthVisit.SelectedValue.AsIntegerOrNull();
                if ( byNthVisit.HasValue && byNthVisit > 2 )
                {
                    nthVisitsTake = byNthVisit.Value;
                }
            }
            bool showNonAttenders = byNthVisit.HasValue && byNthVisit.Value == 0;

            // Get any attendance pattern filters
            int? attendedMinCount = null;
            int? attendedMissedCount = null;
            DateRange attendedMissedDateRange = new DateRange();
            if ( radByPattern.Checked )
            {
                attendedMinCount = tbPatternXTimes.Text.AsIntegerOrNull();
                if ( cbPatternAndMissed.Checked )
                {
                    attendedMissedCount = tbPatternMissedXTimes.Text.AsIntegerOrNull();
                    attendedMissedDateRange = new DateRange( drpPatternDateRange.LowerValue, drpPatternDateRange.UpperValue );
                    if ( !attendedMissedDateRange.Start.HasValue || !attendedMissedDateRange.End.HasValue )
                    {
                        nbMissedDateRangeRequired.Visible = true;
                        return;
                    }
                }
            }
            nbMissedDateRangeRequired.Visible = false;

            // Determine how dates shold be grouped
            ChartGroupBy groupBy = hfGroupBy.Value.ConvertToEnumOrNull<ChartGroupBy>() ?? ChartGroupBy.Week;

            // Determine if parents or children are being included with results
            var includeParents = hfViewBy.Value.ConvertToEnumOrNull<ViewBy>().GetValueOrDefault( ViewBy.Attendees ) == ViewBy.ParentsOfAttendees;
            var includeChildren = hfViewBy.Value.ConvertToEnumOrNull<ViewBy>().GetValueOrDefault( ViewBy.Attendees ) == ViewBy.ChildrenOfAttendees;

            // Atttendance results
            var allAttendeeVisits = new Dictionary<int, AttendeeVisits>();
            var allResults = new List<AttendeeResult>();

            // Collection of async queries to run before assembling data
            var qryTasks = new List<Task>();

            DataTable dtAttendeeLastAttendance = null;
            DataTable dtAttendees = null;
            DataTable dtAttendeeFirstDates = null;
            List<int> personIdsWhoDidNotMiss = null;

            if ( !showNonAttenders )
            {
                // Call the stored procedure to get all the person ids and their attendance dates for anyone
                // whith attendance that matches the selected criteria.
                qryTasks.Add( Task.Run( () =>
                {
                    DataTable dtAttendeeDates = AttendanceService.GetAttendanceAnalyticsAttendeeDates(
                        groupIdList, start, end, campusIdList, includeNullCampus, scheduleIdList ).Tables[0];

                    foreach ( DataRow row in dtAttendeeDates.Rows )
                    {
                        int personId = (int)row["PersonId"];
                        allAttendeeVisits.AddOrIgnore( personId, new AttendeeVisits() );
                        var result = allAttendeeVisits[personId];
                        result.PersonId = personId;

                        DateTime summaryDate = DateTime.MinValue;
                        switch ( groupBy )
                        {
                            case ChartGroupBy.Week: summaryDate = (DateTime)row["SundayDate"]; break;
                            case ChartGroupBy.Month: summaryDate = (DateTime)row["MonthDate"]; break;
                            case ChartGroupBy.Year: summaryDate = (DateTime)row["YearDate"]; break;
                        }
                        if ( !result.AttendanceSummary.Contains( summaryDate ) )
                        {
                            result.AttendanceSummary.Add( summaryDate );
                        }
                    }
                } ) );

                // Call the stored procedure to get the last attendance
                qryTasks.Add( Task.Run( () =>
                {
                    dtAttendeeLastAttendance = AttendanceService.GetAttendanceAnalyticsAttendeeLastAttendance(
                        groupIdList, start, end, campusIdList, includeNullCampus, scheduleIdList ).Tables[0];
                } ) );

                // Call the stored procedure to get the names/demographic info for attendess
                qryTasks.Add( Task.Run( () =>
                {
                    dtAttendees = AttendanceService.GetAttendanceAnalyticsAttendees(
                        groupIdList, start, end, campusIdList, includeNullCampus, scheduleIdList, includeParents, includeChildren ).Tables[0];
                } ) );

                // If checking for missed attendance, get the people who missed that number of dates during the missed date range
                if ( attendedMissedCount.HasValue &&
                    attendedMissedDateRange.Start.HasValue &&
                    attendedMissedDateRange.End.HasValue )
                {
                    qryTasks.Add( Task.Run( () =>
                    {
                        personIdsWhoDidNotMiss = new List<int>();

                        DataTable dtAttendeeDatesMissed = AttendanceService.GetAttendanceAnalyticsAttendeeDates(
                            groupIdList, attendedMissedDateRange.Start.Value, attendedMissedDateRange.End.Value,
                            campusIdList, includeNullCampus, scheduleIdList ).Tables[0];

                        var missedResults = new Dictionary<int, AttendeeResult>();
                        foreach ( DataRow row in dtAttendeeDatesMissed.Rows )
                        {
                            int personId = (int)row["PersonId"];
                            missedResults.AddOrIgnore( personId, new AttendeeResult() );
                            var missedResult = missedResults[personId];
                            missedResult.PersonId = personId;

                            DateTime summaryDate = DateTime.MinValue;
                            switch ( groupBy )
                            {
                                case ChartGroupBy.Week: summaryDate = (DateTime)row["SundayDate"]; break;
                                case ChartGroupBy.Month: summaryDate = (DateTime)row["MonthDate"]; break;
                                case ChartGroupBy.Year: summaryDate = (DateTime)row["YearDate"]; break;
                            }

                            if ( !missedResult.AttendanceSummary.Contains( summaryDate ) )
                            {
                                missedResult.AttendanceSummary.Add( summaryDate );
                            }
                        }

                        var missedPossibleDates = GetPossibleAttendancesForDateRange( attendedMissedDateRange, groupBy );
                        int missedPossibleCount = missedPossibleDates.Count();

                        personIdsWhoDidNotMiss = missedResults
                            .Where( m => missedPossibleCount - m.Value.AttendanceSummary.Count < attendedMissedCount.Value )
                            .Select( m => m.Key )
                            .ToList();
                    } ) );
                }

                // Call the stored procedure to get the first five dates that any person attended this group type
                qryTasks.Add( Task.Run( () =>
                {
                    dtAttendeeFirstDates = AttendanceService.GetAttendanceAnalyticsAttendeeFirstDates(
                        groupTypeIdList, groupIdList, start, end, campusIdList, includeNullCampus, scheduleIdList ).Tables[0];
                } ) );
            }
            else
            {
                qryTasks.Add( Task.Run( () =>
                {
                    DataSet ds = AttendanceService.GetAttendanceAnalyticsNonAttendees(
                        groupTypeIdList, groupIdList, start, end, campusIdList, includeNullCampus, scheduleIdList, includeParents, includeChildren );

                    DataTable dtNonAttenders = ds.Tables[0];
                    dtAttendeeFirstDates = ds.Tables[1];
                    dtAttendeeLastAttendance = ds.Tables[2];

                    foreach ( DataRow row in dtNonAttenders.Rows )
                    {
                        int personId = (int)row["Id"];

                        var result = new AttendeeResult();
                        result.PersonId = personId;

                        var person = new PersonInfo();
                        person.NickName = row["NickName"].ToString();
                        person.LastName = row["LastName"].ToString();
                        person.Email = row["Email"].ToString();
                        person.Birthdate = row["BirthDate"] as DateTime?;
                        person.Age = Person.GetAge( person.Birthdate );

                        person.ConnectionStatusValueId = row["ConnectionStatusValueId"] as int?;
                        result.Person = person;

                        if ( includeParents )
                        {
                            result.ParentId = (int)row["ParentId"];
                            var parent = new PersonInfo();
                            parent.NickName = row["ParentNickName"].ToString();
                            parent.LastName = row["ParentLastName"].ToString();
                            parent.Email = row["ParentEmail"].ToString();
                            parent.Birthdate = row["ParentBirthDate"] as DateTime?;
                            parent.Age = Person.GetAge( parent.Birthdate );
                            result.Parent = parent;
                        }

                        if ( includeChildren )
                        {
                            var child = new PersonInfo();
                            result.ChildId = (int)row["ChildId"];
                            child.NickName = row["ChildNickName"].ToString();
                            child.LastName = row["ChildLastName"].ToString();
                            child.Email = row["ChildEmail"].ToString();
                            child.Birthdate = row["ChildBirthDate"] as DateTime?;
                            child.Age = Person.GetAge( child.Birthdate );
                            result.Child = child;
                        }

                        allResults.Add( result );
                    }
                } ) );
            }

            // If a dataview filter was included, find the people who match that criteria
            List<int> dataViewPersonIds = null;
            qryTasks.Add( Task.Run( () =>
            {
                var dataViewId = dvpDataView.SelectedValueAsInt();
                if ( dataViewId.HasValue )
                {
                    dataViewPersonIds = new List<int>();
                    var dataView = new DataViewService( _rockContext ).Get( dataViewId.Value );
                    if ( dataView != null )
                    {
                        var errorMessages = new List<string>();
                        var dvPersonService = new PersonService( _rockContext );
                        ParameterExpression paramExpression = dvPersonService.ParameterExpression;
                        Expression whereExpression = dataView.GetExpression( dvPersonService, paramExpression, out errorMessages );

                        SortProperty sort = null;
                        var dataViewPersonIdQry = dvPersonService
                            .Queryable().AsNoTracking()
                            .Where( paramExpression, whereExpression, sort )
                            .Select( p => p.Id );
                        dataViewPersonIds = dataViewPersonIdQry.ToList();
                    }
                }
            } ) );

            // Wait for all the queries to finish
            Task.WaitAll( qryTasks.ToArray() );

            if ( !showNonAttenders )
            {
                var attendees = allAttendeeVisits.AsQueryable();

                // If dataview filter was included remove anyone not in that dataview
                if ( dataViewPersonIds != null )
                {
                    attendees = attendees.Where( p => dataViewPersonIds.Contains( p.Key ) );
                }

                // If filter for number missed was included, remove anyone who did not match that filter
                if ( personIdsWhoDidNotMiss != null )
                {
                    attendees = attendees.Where( p => !personIdsWhoDidNotMiss.Contains( p.Key ) );
                }

                // If filtering by minimum times attended
                if ( attendedMinCount.HasValue )
                {
                    attendees = attendees.Where( p => p.Value.AttendanceSummary.Count() >= attendedMinCount );
                }

                // Force filter application
                allAttendeeVisits = attendees.ToDictionary( k => k.Key, v => v.Value );

                // Add the First Visit information
                foreach ( DataRow row in dtAttendeeFirstDates.Rows )
                {
                    int personId = (int)row["PersonId"];
                    if ( allAttendeeVisits.ContainsKey( personId ) )
                    {
                        allAttendeeVisits[personId].FirstVisits.Add( (DateTime)row["StartDate"] );
                    }
                }

                // If filtering based on visit time, only include those who visited the selected time during the date range
                if ( byNthVisit.HasValue )
                {
                    int skipCount = byNthVisit.Value - 1;
                    allAttendeeVisits = allAttendeeVisits
                        .Where( p => p.Value.FirstVisits.Skip( skipCount ).Take( 1 ).Any( d => d >= start && d < end ) )
                        .ToDictionary( k => k.Key, v => v.Value );
                }

                // Add the Last Attended information
                if ( dtAttendeeLastAttendance != null )
                {
                    foreach ( DataRow row in dtAttendeeLastAttendance.Rows )
                    {
                        int personId = (int)row["PersonId"];
                        if ( allAttendeeVisits.ContainsKey( personId ) )
                        {
                            var result = allAttendeeVisits[personId];
                            if ( result.LastVisit == null )
                            {
                                var lastAttendance = new PersonLastAttendance();
                                lastAttendance.CampusId = row["CampusId"] as int?;
                                lastAttendance.GroupId = row["GroupId"] as int?;
                                lastAttendance.GroupName = row["GroupName"].ToString();
                                lastAttendance.RoleName = row["RoleName"].ToString();
                                lastAttendance.InGroup = !string.IsNullOrWhiteSpace( lastAttendance.RoleName );
                                lastAttendance.ScheduleId = row["ScheduleId"] as int?;
                                lastAttendance.StartDateTime = (DateTime)row["StartDateTime"];
                                lastAttendance.LocationId = row["LocationId"] as int?;
                                lastAttendance.LocationName = row["LocationName"].ToString();
                                result.LastVisit = lastAttendance;
                            }
                        }
                    }
                }

                // Add the Demographic information
                if ( dtAttendees != null )
                {
                    var newResults = new Dictionary<int, AttendeeResult>();

                    foreach ( DataRow row in dtAttendees.Rows )
                    {
                        int personId = (int)row["Id"];
                        if ( allAttendeeVisits.ContainsKey( personId ) )
                        {
                            var result = new AttendeeResult( allAttendeeVisits[personId] );

                            var person = new PersonInfo();
                            person.NickName = row["NickName"].ToString();
                            person.LastName = row["LastName"].ToString();
                            person.Email = row["Email"].ToString();
                            person.Birthdate = row["BirthDate"] as DateTime?;
                            person.Age = Person.GetAge( person.Birthdate );
                            person.ConnectionStatusValueId = row["ConnectionStatusValueId"] as int?;
                            result.Person = person;

                            if ( includeParents )
                            {
                                result.ParentId = (int)row["ParentId"];
                                var parent = new PersonInfo();
                                parent.NickName = row["ParentNickName"].ToString();
                                parent.LastName = row["ParentLastName"].ToString();
                                parent.Email = row["ParentEmail"].ToString();
                                parent.Birthdate = row["ParentBirthDate"] as DateTime?;
                                parent.Age = Person.GetAge( parent.Birthdate );
                                result.Parent = parent;
                            }

                            if ( includeChildren )
                            {
                                var child = new PersonInfo();
                                result.ChildId = (int)row["ChildId"];
                                child.NickName = row["ChildNickName"].ToString();
                                child.LastName = row["ChildLastName"].ToString();
                                child.Email = row["ChildEmail"].ToString();
                                child.Birthdate = row["ChildBirthDate"] as DateTime?;
                                child.Age = Person.GetAge( child.Birthdate );
                                result.Child = child;
                            }

                            allResults.Add( result );
                        }
                    }
                }
            }
            else
            {
                // If dataview filter was included remove anyone not in that dataview
                if ( dataViewPersonIds != null )
                {
                    allResults = allResults
                        .Where( p => dataViewPersonIds.Contains( p.PersonId ) )
                        .ToList();
                }

                // Add the first visit dates for people
                foreach ( DataRow row in dtAttendeeFirstDates.Rows )
                {
                    int personId = (int)row["PersonId"];
                    foreach ( var result in allResults.Where( r => r.PersonId == personId ) )
                    {
                        result.FirstVisits.Add( (DateTime)row["StartDate"] );
                    }
                }

                // Add the Last Attended information
                if ( dtAttendeeLastAttendance != null )
                {
                    foreach ( DataRow row in dtAttendeeLastAttendance.Rows )
                    {
                        int personId = (int)row["PersonId"];
                        foreach ( var result in allResults.Where( r => r.PersonId == personId ) )
                        {
                            if ( result.LastVisit == null )
                            {
                                var lastAttendance = new PersonLastAttendance();
                                lastAttendance.CampusId = row["CampusId"] as int?;
                                lastAttendance.GroupId = row["GroupId"] as int?;
                                lastAttendance.GroupName = row["GroupName"].ToString();
                                lastAttendance.RoleName = row["RoleName"].ToString();
                                lastAttendance.InGroup = !string.IsNullOrWhiteSpace( lastAttendance.RoleName );
                                lastAttendance.ScheduleId = row["ScheduleId"] as int?;
                                lastAttendance.StartDateTime = (DateTime)row["StartDateTime"];
                                lastAttendance.LocationId = row["LocationId"] as int?;
                                lastAttendance.LocationName = row["LocationName"].ToString();
                                result.LastVisit = lastAttendance;
                            }
                        }
                    }
                }
            }

            // Begin formatting the columns
            var qryResult = allResults.AsQueryable();

            var personUrlFormatString = ( (RockPage)this.Page ).ResolveRockUrl( "~/Person/{0}" );

            var personHyperLinkField = gAttendeesAttendance.Columns.OfType<HyperLinkField>().FirstOrDefault( a => a.HeaderText == "Name" );
            if ( personHyperLinkField != null )
            {
                personHyperLinkField.DataNavigateUrlFormatString = personUrlFormatString;
            }

            var parentHyperLinkField = gAttendeesAttendance.Columns.OfType<HyperLinkField>().FirstOrDefault( a => a.HeaderText == "Parent" );
            if ( parentHyperLinkField != null )
            {
                parentHyperLinkField.Visible = includeParents;
                parentHyperLinkField.DataNavigateUrlFormatString = personUrlFormatString;
            }

            var parentField = gAttendeesAttendance.Columns.OfType<RockBoundField>().FirstOrDefault( a => a.HeaderText == "Parent" );
            if ( parentField != null )
            {
                parentField.ExcelExportBehavior = includeParents ? ExcelExportBehavior.AlwaysInclude : ExcelExportBehavior.NeverInclude;
            }

            var parentEmailField = gAttendeesAttendance.Columns.OfType<RockBoundField>().FirstOrDefault( a => a.HeaderText == "Parent Email" );
            if ( parentEmailField != null )
            {
                parentEmailField.ExcelExportBehavior = includeParents ? ExcelExportBehavior.AlwaysInclude : ExcelExportBehavior.NeverInclude;
            }

            var childHyperLinkField = gAttendeesAttendance.Columns.OfType<HyperLinkField>().FirstOrDefault( a => a.HeaderText == "Child" );
            if ( childHyperLinkField != null )
            {
                childHyperLinkField.Visible = includeChildren;
                childHyperLinkField.DataNavigateUrlFormatString = personUrlFormatString;
            }

            var childfield = gAttendeesAttendance.Columns.OfType<RockBoundField>().FirstOrDefault( a => a.HeaderText == "Child" );
            if ( childfield != null )
            {
                childfield.ExcelExportBehavior = includeChildren ? ExcelExportBehavior.AlwaysInclude : ExcelExportBehavior.NeverInclude;
            }

            var childEmailField = gAttendeesAttendance.Columns.OfType<RockBoundField>().FirstOrDefault( a => a.HeaderText == "Child Email" );
            if ( childEmailField != null )
            {
                childEmailField.ExcelExportBehavior = includeChildren ? ExcelExportBehavior.AlwaysInclude : ExcelExportBehavior.NeverInclude;
            }

            var childAgeField = gAttendeesAttendance.Columns.OfType<RockBoundField>().FirstOrDefault( a => a.HeaderText == "Child Age" );
            if ( childAgeField != null )
            {
                childAgeField.ExcelExportBehavior = includeChildren ? ExcelExportBehavior.AlwaysInclude : ExcelExportBehavior.NeverInclude;
            }

            SortProperty sortProperty = gAttendeesAttendance.SortProperty;

            if ( sortProperty != null )
            {
                if ( sortProperty.Property == "AttendanceSummary.Count" )
                {
                    if ( sortProperty.Direction == SortDirection.Descending )
                    {
                        qryResult = qryResult.OrderByDescending( a => a.AttendanceSummary.Count() );
                    }
                    else
                    {
                        qryResult = qryResult.OrderBy( a => a.AttendanceSummary.Count() );
                    }
                }
                else if ( sortProperty.Property == "FirstVisit.StartDateTime" )
                {
                    if ( sortProperty.Direction == SortDirection.Descending )
                    {
                        qryResult = qryResult.OrderByDescending( a => a.FirstVisits.Min() );
                    }
                    else
                    {
                        qryResult = qryResult.OrderBy( a => a.FirstVisits.Min() );
                    }
                }
                else
                {
                    qryResult = qryResult.Sort( sortProperty );
                }
            }
            else
            {
                qryResult = qryResult.OrderBy( a => a.Person.LastName ).ThenBy( a => a.Person.NickName );
            }

            var attendancePercentField = gAttendeesAttendance.Columns.OfType<RockTemplateField>().First( a => a.HeaderText.EndsWith( "Attendance %" ) );
            attendancePercentField.HeaderText = string.Format( "{0}ly Attendance %", groupBy.ConvertToString() );

            // Calculate all the possible attendance summary dates
            UpdatePossibleAttendances( dateRange, groupBy );

            // pre-load the schedule names since FriendlyScheduleText requires building the ICal object, etc
            _scheduleNameLookup = new ScheduleService( _rockContext ).Queryable()
                .ToList()
                .ToDictionary( k => k.Id, v => v.FriendlyScheduleText );

            if ( includeParents )
            {
                gAttendeesAttendance.PersonIdField = "ParentId";
                gAttendeesAttendance.DataKeyNames = new string[] { "ParentId", "PersonId" };
            }
            else if ( includeChildren )
            {
                gAttendeesAttendance.PersonIdField = "ChildId";
                gAttendeesAttendance.DataKeyNames = new string[] { "ChildId", "PersonId" };
            }
            else
            {
                gAttendeesAttendance.PersonIdField = "PersonId";
                gAttendeesAttendance.DataKeyNames = new string[] { "PersonId" };
            }

            // Create the dynamic attendance grid columns as needed
            CreateDynamicAttendanceGridColumns();

            try
            {
                nbAttendeesError.Visible = false;

                gAttendeesAttendance.SetLinqDataSource( qryResult );
                var currentPageItems = gAttendeesAttendance.DataSource as List<AttendeeResult>;
                if ( currentPageItems != null )
                {
                    var currentPagePersonIds = new List<int>();
                    if ( includeParents )
                    {
                        currentPagePersonIds = currentPageItems.Select( i => i.ParentId ).ToList();
                        gAttendeesAttendance.PersonIdField = "ParentId";
                        gAttendeesAttendance.DataKeyNames = new string[] { "ParentId", "PersonId" };
                    }
                    else if ( includeChildren )
                    {
                        currentPagePersonIds = currentPageItems.Select( i => i.ChildId ).ToList();
                        gAttendeesAttendance.PersonIdField = "ChildId";
                        gAttendeesAttendance.DataKeyNames = new string[] { "ChildId", "PersonId" };
                    }
                    else
                    {
                        currentPagePersonIds = currentPageItems.Select( i => i.PersonId ).ToList();
                        gAttendeesAttendance.PersonIdField = "PersonId";
                        gAttendeesAttendance.DataKeyNames = new string[] { "PersonId" };
                    }

                    LoadCurrentPageObjects( currentPagePersonIds );
                }

                _currentlyExporting = isExporting;
                gAttendeesAttendance.DataBind();
                _currentlyExporting = false;
            }
            catch ( Exception exception )
            {
                LogAndShowException( exception );
            }
        }