public IActionResult Put(string id, [FromBody] PersonEntry person)
        {
            var insane = SanityCheckUpdate(id, person);

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

            lock (_contextLock)
            {
                PersonEntry existing = GetExistingPerson(id);
                if (existing == null)
                {
                    return(NotFound(_localizer[Strings.PersonIdNotFound, id].Value));
                }

                // DB objects often need special care, particularly regarding their Ids, when updating.
                // Do a deep copy from person to existing where the existing object keeps its own Ids.
                existing.Copy(person);

                // NOTE: there is a race condition between GetExisting() and Update() calls
                _context.PersonEntries.Update(existing);
                _context.SaveChanges();

                return(NoContent());
            }
        }
Example #2
0
        public void Post_Successful_IgnoresInputId(string id)
        {
            PersonEntry entry = new PersonEntry
            {
                Id        = id,
                FirstName = "first",
                LastName  = "last"
            };
            var result = _controller.Post(entry);

            Assert.IsType <CreatedAtRouteResult>(result);

            CreatedAtRouteResult car = (CreatedAtRouteResult)result;

            Assert.Equal(201, car.StatusCode);
            Assert.Equal("GetPersonById", car.RouteName);
            Assert.IsAssignableFrom <PersonEntry>(car.Value);

            PersonEntry created = (PersonEntry)car.Value;

            Assert.Equal("first", created.FirstName);
            Assert.Equal("last", created.LastName);

            // The Id is coming back null, but in a real post it shows up
            // I expect it has to do with the DB context mock not being setup correctly
            // Assert.False(string.IsNullOrWhiteSpace(created.Id));
            // Assert.NotEqual(id, created.Id);

            VerifyAddPerson();
            VerifySaveDbOnce();
        }
Example #3
0
        public ActionResult Create(PersonEntry entry)
        {
            entry.DateAdded = DateTime.Now;
            _db.Entries.Add(entry);
            _db.SaveChanges();

            return(Content("New entry successfully added."));
        }
        /// <summary>
        /// Store an avatar image in the people DB.
        /// </summary>
        /// <param name="image">The avatar image to store.</param>
        /// <returns>Http bad request status if the image is empty,
        /// http conflict status if the person Id on the given image is not empty and
        /// does not match the person Id in the DB for the given image.</returns>
        protected IActionResult StoreAvatarImage(ImageEntry image)
        {
            if (image == null || image.Data == null || image.Data.Length == 0)
            {
                return(BadRequest(_localizer[Strings.EmptyImageData].Value));
            }

            PersonEntry person = null;

            if (!string.IsNullOrWhiteSpace(image.PersonId))
            {
                person = GetExistingPerson(image.PersonId);
                if (person == null)
                {
                    return(BadRequest(_localizer[Strings.PersonIdNotFound, image.PersonId].Value));
                }
            }

            lock (_contextLock)
            {
                ImageEntry existing = null;
                if (!string.IsNullOrWhiteSpace(image.Id))
                {
                    existing = GetExistingImage(image.Id);
                    if (existing != null)
                    {
                        // updating an existing entry, make sure person ID in new image entry matches
                        if (!string.IsNullOrWhiteSpace(existing.PersonId) &&
                            !existing.PersonId.Equals(image.PersonId))
                        {
                            return(Conflict(_localizer[Strings.PersonIdMismatch].Value));
                        }
                    }
                }

                if (existing == null)
                {
                    // make sure a new Id is generated
                    image.Id = null;
                    _context.ImageEntries.Add(image);
                }
                else
                {
                    existing.Data     = image.Data;
                    existing.PersonId = image.PersonId;
                    _context.ImageEntries.Update(existing);
                }

                if (person != null)
                {
                    person.AvatarId = image.Id;
                    _context.PersonEntries.Update(person);
                }

                _context.SaveChanges();
                return(Ok());
            }
        }
Example #5
0
        public void Post_EmptyOrMissingFields_ReturnsBadRequest(string first, string last)
        {
            PersonEntry entry = new PersonEntry
            {
                FirstName = first,
                LastName  = last
            };
            var result = _controller.Post(entry);

            Assert.IsType <BadRequestObjectResult>(result);
            VerifyNoDbChanges();
        }
Example #6
0
        public void Put_IdMismatch_ReturnsBadRequest()
        {
            PersonEntry entry = new PersonEntry
            {
                Id        = "1",
                FirstName = "first",
                LastName  = "last"
            };
            var result = _controller.Put("2", entry);

            Assert.IsType <BadRequestObjectResult>(result);
            VerifyNoDbChanges();
        }
        public ActionResult <PersonEntry> GetPersonById(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return(BadRequest(_localizer[Strings.EmptyPersonId].Value));
            }
            PersonEntry entry = GetExistingPerson(id);

            if (entry == null)
            {
                return(NotFound(_localizer[Strings.PersonIdNotFound, id].Value));
            }
            return(entry);
        }
Example #8
0
        public void Put_Successful(string id, string first, string last)
        {
            PersonEntry entry = new PersonEntry
            {
                Id        = id,
                FirstName = first,
                LastName  = last
            };
            var result = _controller.Put(id, entry);

            Assert.IsType <NoContentResult>(result);
            VerifyUpdatePerson();
            VerifySaveDbOnce();
        }
 /// <summary>
 /// Perform sanity checks on PersonEntry object for ADD to people DB.
 /// </summary>
 /// <param name="person">The person object to validate.</param>
 /// <returns>null if sane, otherwise an ActionResult with the appropriate error status.</returns>
 protected IActionResult SanityCheckAdd(PersonEntry person)
 {
     if (person == null)
     {
         return(BadRequest(_localizer[Strings.UnrecognizedJsonObject].Value));
     }
     if (string.IsNullOrWhiteSpace(person.FirstName))
     {
         return(BadRequest(_localizer[Strings.EmptyPersonFirstName].Value));
     }
     if (string.IsNullOrWhiteSpace(person.LastName))
     {
         return(BadRequest(_localizer[Strings.EmptyPersonLastName].Value));
     }
     return(null);
 }
Example #10
0
        public void RunTest()
        {
            const string name1 = "Henry has a first name!";
            const string name2 = "Larry doesn't have a last name!";
            var          key1  = new PersonKey(name1);
            var          key2  = new PersonKey(name2);

            var personEntry1 = new PersonEntry(key1, 10);
            var personEntry2 = new PersonEntry(key2, 5);

            var thresholdsByKey = new Dictionary <PersonKey, int>();

            thresholdsByKey.Add(key1, 30);
            thresholdsByKey.Add(key2, 2);

            var levelRemovalProcessor   = new RemovalByLevelThresholdProcessor(thresholdsByKey);
            var friendClearingProcessor = new FriendClearingProcessor();

            var serializer = new PofSerializer(context);

            using (var ms = new MemoryStream()) {
                using (var writer = new BinaryWriter(ms, Encoding.UTF8, true)) {
                    serializer.Serialize(writer, levelRemovalProcessor);
                    serializer.Serialize(writer, friendClearingProcessor);
                }
                ms.Position = 0;
                Console.WriteLine(ms.ToArray().ToHex());
                using (var reader = new BinaryReader(ms)) {
                    levelRemovalProcessor   = serializer.Deserialize <RemovalByLevelThresholdProcessor>(reader);
                    friendClearingProcessor = serializer.Deserialize <FriendClearingProcessor>(reader);
                }
            }

            var entry1 = new Entry <PersonKey, PersonEntry>(key1, personEntry1);
            var entry2 = new Entry <PersonKey, PersonEntry>(key2, personEntry2);

            friendClearingProcessor.Process(entry1);
            friendClearingProcessor.Process(entry2);

            levelRemovalProcessor.Process(entry1);
            levelRemovalProcessor.Process(entry2);

            assertTrue(entry1.IsPresent());
            assertFalse(entry2.IsPresent());
        }
        public IActionResult Post([FromBody] PersonEntry person)
        {
            var insane = SanityCheckAdd(person);

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

            lock (_contextLock) {
                // make sure a new Id is generated
                person.Id = null;

                _context.PersonEntries.Add(person);
                _context.SaveChanges();

                return(CreatedAtRoute("GetPersonById", new { id = person.Id }, person));
            }
        }
        public IActionResult Delete(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return(BadRequest(_localizer[Strings.EmptyPersonId].Value));
            }

            lock (_contextLock)
            {
                PersonEntry person = GetExistingPerson(id);
                if (person == null)
                {
                    return(NotFound(_localizer[Strings.PersonIdNotFound, id].Value));
                }

                _context.PersonEntries.Remove(person);
                _context.SaveChanges();

                return(NoContent());
            }
        }
Example #13
0
 /// <summary>
 /// Update all members except Id using the values from the given PersonEntry object.
 /// </summary>
 /// <param name="other">The PersonEntry object to get updated values from.</param>
 /// <returns>Self</returns>
 public PersonEntry Copy(PersonEntry other)
 {
     // This could also be done with serialization/deserialization or reflection so
     // this method doesn't have to be updated any time the PersonEntry structure changes.
     if (other != null && other != this)
     {
         FirstName = other.FirstName;
         LastName = other.LastName;
         Gender = other.Gender;
         Age = other.Age;
         Interests = other.Interests;
         AvatarId = other.AvatarId;
         Addr1 = other.Addr1;
         Addr2 = other.Addr2;
         Country = other.Country;
         State = other.State;
         City = other.City;
         ZipCode = other.ZipCode;
     }
     return this;
 }
 /// <summary>
 /// Perform sanity checks on PersonEntry object for UPDATE to people DB.
 /// </summary>
 /// <param name="person">The person object to validate.</param>
 /// <returns>null if sane, otherwise an ActionResult with the appropriate error status.</returns>
 protected IActionResult SanityCheckUpdate(string id, PersonEntry person)
 {
     if (person == null)
     {
         return(BadRequest(_localizer[Strings.UnrecognizedJsonObject].Value));
     }
     if (string.IsNullOrWhiteSpace(id))
     {
         return(BadRequest(_localizer[Strings.EmptyPersonId].Value));
     }
     if (!string.IsNullOrWhiteSpace(person.Id) && (string.Compare(id, person.Id) != 0))
     {
         return(BadRequest(_localizer[Strings.PersonIdMismatch].Value));
     }
     if (string.IsNullOrWhiteSpace(person.FirstName))
     {
         return(BadRequest(_localizer[Strings.EmptyPersonFirstName].Value));
     }
     if (string.IsNullOrWhiteSpace(person.LastName))
     {
         return(BadRequest(_localizer[Strings.EmptyPersonLastName].Value));
     }
     return(null);
 }
Example #15
0
 public JsonResult AddUnitTestPerson(PersonEntry entry)
 {
     PersonEntries.Add(entry);
     return(Json(entry, JsonRequestBehavior.AllowGet));
 }
                public void SetFamily( Rock.Client.Family primaryFamily, Rock.Client.GuestFamily guestFamily )
                {
                    // store a ref to the primary and guest family
                    PrimaryFamily = primaryFamily;
                    GuestFamily = guestFamily;

                    // remove any current family member from the view hierarchy
                    if ( Container.Subviews.Length > 0 )
                    {
                        foreach ( UIView child in Container.Subviews )
                        {
                            if ( child as UIButton != null )
                            {
                                child.RemoveFromSuperview( );
                            }
                        }
                    }

                    FamilyName.Text = guestFamily.Name;
                    FamilyName.SizeToFit( );

                    // add the family name
                    Container.AddSubview( FamilyName );

                    // add our "Add Family Member" button
                    Container.AddSubview( EditGuestFamilyButton );

                    // setup our list
                    Members = new List<PersonEntry>( guestFamily.FamilyMembers.Count );

                    // for each family member, create a person entry and add them to the cell
                    foreach ( Rock.Client.GuestFamily.Member familyMember in guestFamily.FamilyMembers )
                    {
                        // create and add the person entry
                        PersonEntry personEntry = new PersonEntry( familyMember.FirstName, familyMember.Id, familyMember.CanCheckin, familyMember.Role, primaryFamily.FamilyMembers );
                        Members.Add( personEntry );

                        // add this person to the cell
                        Container.AddSubview( personEntry.Button );
                    }
                }
                public void SetFamily( Rock.Client.Family family )
                {
                    Family = family;

                    // remove any current family member from the view hierarchy
                    if ( Container.Subviews.Length > 0 )
                    {
                        foreach ( UIView child in Container.Subviews )
                        {
                            child.RemoveFromSuperview( );
                        }
                    }

                    // add the "Family Members" label
                    AddSubview( FamilyMembersLabel );

                    // add the Guest label
                    AddSubview( GuestFamily );

                    // add our "Add Family Member" button
                    Container.AddSubview( AddFamilyMemberIcon );

                    // setup our list
                    Members = new List<PersonEntry>( family.FamilyMembers.Count );

                    // for each family member, create a person entry and add them to the cell
                    foreach ( Rock.Client.GroupMember familyMember in family.FamilyMembers )
                    {
                        // create and add the person entry. First see if they're an adult or child
                        bool isChild = familyMember.GroupRole.Id == Config.Instance.FamilyMemberChildGroupRole.Id ? true : false;

                        PersonEntry personEntry = new PersonEntry( familyMember.Person, isChild,
                            delegate(Rock.Client.Person person, NSData imageBuffer )
                            {
                                ParentTableSource.EditFamilyMember( familyMember, imageBuffer );
                            });
                        Members.Add( personEntry );

                        // set their name and age
                        personEntry.SetInfo( );

                        // add this person to the cell
                        Container.AddSubview( personEntry.View );
                    }
                }
Example #18
0
        public void RunTest()
        {
            const string name1 = "Henry has a first name!";
            const string name2 = "Larry doesn't have a last name!";
            var          key1  = new PersonKey(Guid.NewGuid(), name1);
            var          key2  = new PersonKey(Guid.NewGuid(), name2);

            var personEntry1 = new PersonEntry(key1, 10);
            var personEntry2 = new PersonEntry(key2, 5);

            personEntry1.Friends.Add(new PersonFriend(0xAEF8329dF, "Mark"));
            personEntry2.Friends.Add(new PersonFriend(0xF8372D33F, "Henry"));
            personEntry2.Friends.Add(new PersonFriend(0x47928C3ED, "Jane"));

            var thresholdsByKey = new Dictionary <PersonKey, int>();

            thresholdsByKey.Add(key1, 30);
            thresholdsByKey.Add(key2, 2);

            var levelRemovalProcessor   = new RemovalByLevelThresholdProcessor(thresholdsByKey);
            var friendClearingProcessor = new FriendClearingProcessor();

            var serializer = new PofSerializer(context);

            using (var ms = new MemoryStream()) {
                using (var writer = new BinaryWriter(ms, Encoding.UTF8, true)) {
                    serializer.Serialize(writer, levelRemovalProcessor);
                    serializer.Serialize(writer, friendClearingProcessor);
                }
                ms.Position = 0;
                Console.WriteLine(ms.ToArray().ToHex());
                using (var reader = new BinaryReader(ms, Encoding.UTF8, true)) {
                    levelRemovalProcessor   = serializer.Deserialize <RemovalByLevelThresholdProcessor>(reader);
                    friendClearingProcessor = serializer.Deserialize <FriendClearingProcessor>(reader);
                }
            }

            var entry1         = new Entry <PersonKey, PersonEntry>(key1, personEntry1);
            var entry2         = new Entry <PersonKey, PersonEntry>(key2, personEntry2);
            var originalEntry1 = entry1;
            var originalEntry2 = entry2;

            using (var ms = new MemoryStream()) {
                using (var writer = new BinaryWriter(ms, Encoding.UTF8, true)) {
                    serializer.Serialize(writer, entry1);
                    serializer.Serialize(writer, entry2);
                }
                ms.Position = 0;
                Console.WriteLine(ms.ToArray().ToHex());
                using (var reader = new BinaryReader(ms, Encoding.UTF8, true)) {
                    entry1 = serializer.Deserialize <Entry <PersonKey, PersonEntry> >(reader);

                    int frameLength = reader.ReadInt32();
                    var frameBody   = reader.ReadBytes(frameLength);
                    using (var innerMs = new MemoryStream(frameBody))
                        using (var innerReader = new BinaryReader(innerMs, Encoding.UTF8, true)) {
                            entry2 = (Entry <PersonKey, PersonEntry>)serializer.Deserialize(innerReader, SerializationFlags.Lengthless, null);
                        }
                }
            }

            friendClearingProcessor.Process(entry1);
            friendClearingProcessor.Process(entry2);

            levelRemovalProcessor.Process(entry1);
            levelRemovalProcessor.Process(entry2);

            AssertTrue(entry1.IsPresent());
            AssertFalse(entry2.IsPresent());

            using (var ms = new MemoryStream()) {
                using (var writer = new BinaryWriter(ms, Encoding.UTF8, true)) {
                    serializer.Serialize(writer, entry1);
                    serializer.Serialize(writer, entry2);
                }
                ms.Position = 0;
                Console.WriteLine(ms.ToArray().ToHex());
                using (var reader = new BinaryReader(ms, Encoding.UTF8, true)) {
                    entry1 = serializer.Deserialize <Entry <PersonKey, PersonEntry> >(reader);
                    entry2 = serializer.Deserialize <Entry <PersonKey, PersonEntry> >(reader);
                }
            }

            AssertTrue(entry1.IsPresent());
            AssertFalse(entry2.IsPresent());
        }
 public JsonResult AddPerson(PersonEntry person)
 {
     PersonRepository.Persons.AddPerson(person);
     //Einfach die Liste inkl. der neuen Person wieder zurückgeben.
     return(Json(PersonRepository.Persons.GetAllPersons(), JsonRequestBehavior.AllowGet));
 }
        protected override FileProcessingResult MakeOnePlot(ResultFileEntry rfe)
        {
            Profiler.StartPart(Utili.GetCurrentMethodAndClass());
            string plotName = "Location Statistics " + rfe.HouseholdNumberString;
            var    persons  = new List <PersonEntry>();

            if (rfe.FullFileName == null)
            {
                throw new LPGException("filename was null");
            }
            using (var sr = new StreamReader(rfe.FullFileName)) {
                PersonEntry lastPerson = null;
                while (!sr.EndOfStream)
                {
                    var s = sr.ReadLine();
                    if (s == null)
                    {
                        throw new LPGException("File " + rfe.FullFileName + " was empty.");
                    }
                    if (s.StartsWith("----", StringComparison.CurrentCulture))
                    {
                        var s2 = sr.ReadLine();
                        if (s2 == null)
                        {
                            throw new LPGException("readline failed");
                        }
                        lastPerson = new PersonEntry(s2);
                        persons.Add(lastPerson);
                    }
                    else
                    {
                        if (lastPerson == null)
                        {
                            throw new LPGException("lastperson was null");
                        }
                        var cols = s.Split(Parameters.CSVCharacterArr, StringSplitOptions.None);
                        var val  = Utili.ConvertToDoubleWithMessage(cols[2], "LocationStatisticsPlot");
                        if (val > 0)
                        {
                            lastPerson.Percentages.Add(cols[0], val);
                        }
                    }
                }
            }
            foreach (var entry in persons)
            {
                var plotModel1 = new PlotModel
                {
                    LegendBorderThickness = 0,
                    LegendOrientation     = LegendOrientation.Horizontal,
                    LegendPlacement       = LegendPlacement.Outside,
                    LegendPosition        = LegendPosition.BottomCenter
                };
                if (Parameters.ShowTitle)
                {
                    plotModel1.Title = plotName;
                }

                var pieSeries1 = new PieSeries
                {
                    InsideLabelColor      = OxyColors.White,
                    InsideLabelPosition   = 0.8,
                    StrokeThickness       = 2,
                    AreInsideLabelsAngled = true
                };
                foreach (var tuple in entry.Percentages)
                {
                    var name = tuple.Key.Trim();
                    if (name.Length > 30)
                    {
                        name = name.Substring(0, 20) + "...";
                    }
                    var slice = new PieSlice(name, tuple.Value);

                    pieSeries1.Slices.Add(slice);
                }

                plotModel1.Series.Add(pieSeries1);
                var newfilename = "LocationStatistics." + entry.CleanName;
                Save(plotModel1, plotName, rfe.FullFileName, Parameters.BaseDirectory, CalcOption.LocationsFile, newfilename);
            }
            Profiler.StopPart(Utili.GetCurrentMethodAndClass());
            return(FileProcessingResult.ShouldCreateFiles);
        }