Exemple #1
0
    protected void btnAdd_click(object sender, EventArgs e)
    {
        cvDOB.Visible = false;
        if (txtDOB.Text == string.Empty)
        {
            cvDOB.ErrorMessage = "DOB is required.";
            cvDOB.IsValid = false;
            cvDOB.Visible = true;
            return;
        }
        FamilyMember obj = new FamilyMember(mInfo.ID);
        obj.RelationshipID = Convert.ToInt32(ddlRelationship.SelectedItem.Value);
        obj.Firstname = tbFirstName.Text;
        obj.Lastname = tbLastname.Text;
        obj.DOB = Convert.ToDateTime(txtDOB.Text);
        obj.Sex = ddlSex.SelectedItem.Value;
        obj.CurrentStatus = Convert.ToChar(ddlCurrentStatus.SelectedItem.Value );
        obj.LivingStatus = Convert.ToInt32(ddlLivingStatus.SelectedItem.Value);
        obj.DateOfDeath =
            (tbDateOfDeath.Text.Length > 0)? Convert.ToDateTime(tbDateOfDeath.Text):DateTime.Now;
        obj.CauseOfDeath = Convert.ToInt32(ddlCauseOfDeath.SelectedItem.Value);

        obj.Save();

        DisplayFamily();
    }
		public object Deserialize(JsonValue json, JsonMapper mapper)
		{
			FamilyMember family = null;
			if ( json != null && !json.IsNull )
			{
				family = new FamilyMember();
				family.ID           = json.ContainsName("id"          ) ? json.GetValue<string>("id"          ) : String.Empty;
				family.Name         = json.ContainsName("name"        ) ? json.GetValue<string>("name"        ) : String.Empty;
				family.Relationship = json.ContainsName("relationship") ? json.GetValue<string>("relationship") : String.Empty;
			}
			return family;
		}
Exemple #3
0
        public static void AddBirth()
        {
            // Til når brugeren skal vælge doctor og midwife.
            List <Clinician> doctors  = collectionClinicians.Find(r => r.Type == "Doctor").ToList();
            List <Clinician> midWives = collectionClinicians.Find(r => r.Type == "MidWife").ToList();

            Console.WriteLine("\nVelkommen til reservation af fødsel");
            Console.WriteLine("-----------------------------------");

            Console.WriteLine("Hvad er navnet på barnet");
            string childName = Console.ReadLine();

            Console.WriteLine("Hvad er navnet på moderen til barnet");
            string motherName = Console.ReadLine();

            Console.WriteLine("Hvad er navnet på faderen til barnet");
            string fatherName = Console.ReadLine();

            Console.WriteLine("Hvilken dato vil du have reservationen til. Skriv på formen DD/MM/ÅÅÅÅ");
            string dato = Console.ReadLine();

            string[] datoOpsplittet = dato.Split("/");
            int      dag            = int.Parse(datoOpsplittet[0]);
            int      måned          = int.Parse(datoOpsplittet[1]);
            int      år             = int.Parse(datoOpsplittet[2]);

            Console.WriteLine("Hvilken tid vil du have reservationen. Skriv på formen TT.MM");
            string tid = Console.ReadLine();

            string[] tidOpsplittet = tid.Split(".");
            int      time          = int.Parse(tidOpsplittet[0]);
            int      minut         = int.Parse(tidOpsplittet[1]);

            Console.WriteLine("Hvilken jordmor vil du gerne have? Indtast tallet ud fra personen");
            int counter = 0;

            foreach (var mW in midWives)
            {
                Console.WriteLine(counter + ". " + mW.FullName);
                counter++;
            }

            int valgtMidwife = int.Parse(Console.ReadLine());

            counter = 0;
            Console.WriteLine("Hvilken doktor vil du gerne have? Indtast tallet ud fra personen");
            foreach (var dc in doctors)
            {
                Console.WriteLine(counter + ". " + dc.FullName);
                counter++;
            }

            int valgtDoctor = int.Parse(Console.ReadLine());

            Console.WriteLine("Du skal også have et fødselsrum reserveret, Vi finder ledige rum for dagen. \n Indtast tallet ud fra rummet");
            var  birthrooms      = showAvailableRooms(new DateTime(år, måned, dag, time, minut, 00, DateTimeKind.Utc), new DateTime(år, måned, dag, time, minut, 00, DateTimeKind.Utc) + TimeSpan.FromHours(5), "BirthRoom");
            int  valgtRumId      = int.Parse(Console.ReadLine());
            Room chosenBirthRoom = birthrooms.Find(r => r.RoomId == valgtRumId);

            Console.WriteLine("Vil du også reservere et Maternityroom y/n");
            Room chosenMaternityRoom = null;

            if (Console.ReadLine().ToLower() == "y")
            {
                Console.WriteLine("MaternityRoom reservation \n Indtast tallet ud fra rummet");
                var maternityRooms = showAvailableRooms(new DateTime(år, måned, dag, time, minut, 00, DateTimeKind.Utc), new DateTime(år, måned, dag, time, minut, 00, DateTimeKind.Utc) + TimeSpan.FromDays(5), "Maternity Room");
                valgtRumId          = int.Parse(Console.ReadLine());
                chosenMaternityRoom = maternityRooms.Find(r => r.RoomId == valgtRumId);
            }
            Console.WriteLine("Vil du også reservere et restingroom y/n");
            Room chosenRestingRoom = null;

            if (Console.ReadLine().ToLower() == "y")
            {
                Console.WriteLine("RestingRoom reservation \n Indtast tallet ud fra rummet");
                var restingRooms = showAvailableRooms(new DateTime(år, måned, dag, time, minut, 00, DateTimeKind.Utc), new DateTime(år, måned, dag, time, minut, 00, DateTimeKind.Utc) + TimeSpan.FromHours(4), "Resting Room");
                valgtRumId        = int.Parse(Console.ReadLine());
                chosenRestingRoom = restingRooms.Find(r => r.RoomId == valgtRumId);
            }

            Console.WriteLine("Tak for dit info, vores super database vil nu oprette reservationen for dig");

            // Følgende kode opsætter de rigtige referencer m.m. Så dataen kan gemmes på databasen
            // Her oprettes de forskellige klasser
            Child        child1  = new Child(childName);
            Birth        birth1  = new Birth();
            Mother       mother1 = new Mother(motherName);
            FamilyMember father1 = new FamilyMember(fatherName, "Father");

            // Her sættes referencer
            // Mother, child, father and birth
            birth1.Child = child1;
            DateTime PST = new DateTime(år, måned, dag, time, minut, 00, DateTimeKind.Utc);

            birth1.PlannedStartTime = PST;
            child1.Mother           = mother1;
            child1.FamilyMembersId  = new List <int>();
            child1.FamilyMembersId.Add(father1.PersonId);
            mother1.Children = new List <int>();
            mother1.Children.Add(child1.PersonId);

            // Clinicians references
            doctors[valgtDoctor].AssociatedBirthsId = new List <int>();
            doctors[valgtDoctor].AssociatedBirthsId.Add(birth1.BirthId);
            midWives[valgtMidwife].AssociatedBirthsId = new List <int>();
            midWives[valgtMidwife].AssociatedBirthsId.Add(birth1.BirthId);
            // Her sættes clinicians på selve birth
            birth1.CliniciansId = new List <int>();
            birth1.CliniciansId.Add(doctors[valgtDoctor].PersonId);
            birth1.CliniciansId.Add(midWives[valgtMidwife].PersonId);

            // Her sættes reservationerne for alle rum.
            Reservation res1 = new Reservation();

            res1.ReservationStart        = new DateTime(år, måned, dag, time, minut, 00, DateTimeKind.Utc);
            res1.ReservationEnd          = res1.ReservationStart + TimeSpan.FromHours(5);
            res1.UserId                  = mother1.PersonId;
            res1.ReservedRoomId          = chosenBirthRoom.RoomId;
            mother1.Reservations         = new List <Reservation>();
            chosenBirthRoom.Reservations = new List <Reservation>();
            mother1.Reservations.Add(res1);
            chosenBirthRoom.Reservations.Add(res1);

            Reservation res2 = new Reservation();

            if (chosenMaternityRoom != null)
            {
                res2.ReservationStart            = new DateTime(år, måned, dag, time, minut, 00, DateTimeKind.Utc);
                res2.ReservationEnd              = res2.ReservationStart + TimeSpan.FromDays(5);
                res2.UserId                      = mother1.PersonId;
                res2.ReservedRoomId              = chosenMaternityRoom.RoomId;
                chosenMaternityRoom.Reservations = new List <Reservation>();
                mother1.Reservations.Add(res2);
                chosenMaternityRoom.Reservations.Add(res2);
            }

            Reservation res3 = new Reservation();

            if (chosenRestingRoom != null)
            {
                res3.ReservationStart          = new DateTime(år, måned, dag, time, minut, 00, DateTimeKind.Utc) + TimeSpan.FromHours(5);
                res3.ReservationEnd            = res3.ReservationStart + TimeSpan.FromHours(4);
                res3.UserId                    = mother1.PersonId;
                res3.ReservedRoomId            = chosenRestingRoom.RoomId;
                chosenRestingRoom.Reservations = new List <Reservation>();
                mother1.Reservations.Add(res3);
                chosenRestingRoom.Reservations.Add(res3);
            }
            // Alt gemmes og reservationen er gemmenført
            // Insert
            collectionBirths.InsertOne(birth1);
            // Mother and child can be found under the specific birth
            collectionOtherPersons.InsertOne(father1);

            // Update Clinicians
            var doctorfilter = Builders <Clinician> .Filter.Eq("PersonId", doctors[valgtDoctor].PersonId);

            var doctorUpdate = Builders <Clinician> .Update.Push("AssociatedBirthsId", birth1.BirthId);

            var result = collectionClinicians.UpdateOne(doctorfilter, doctorUpdate);

            var midwifefilter = Builders <Clinician> .Filter.Eq("PersonId", midWives[valgtMidwife].PersonId);

            var midwifeUpdate = Builders <Clinician> .Update.Push("AssociatedBirthsId", birth1.BirthId);

            var result2 = collectionClinicians.UpdateOne(midwifefilter, midwifeUpdate);
            // Update Rooms
            var birthroomfilter = Builders <Room> .Filter.Eq("RoomId", chosenBirthRoom.RoomId);

            var birthroomupdate = Builders <Room> .Update.Push("Reservations", res1);

            var resultroom1 = collectionRooms.UpdateOne(birthroomfilter, birthroomupdate);

            if (chosenMaternityRoom != null)
            {
                var maternityroomfilter = Builders <Room> .Filter.Eq("RoomId", chosenMaternityRoom.RoomId);

                var maternityroomupdate = Builders <Room> .Update.Push("Reservations", res2);

                var resultroom2 = collectionRooms.UpdateOne(maternityroomfilter, maternityroomupdate);
            }

            if (chosenRestingRoom != null)
            {
                var restroomfilter = Builders <Room> .Filter.Eq("RoomId", chosenRestingRoom.RoomId);

                var restroomupdate = Builders <Room> .Update.Push("Reservations", res3);

                var resultroom3 = collectionRooms.UpdateOne(restroomfilter, restroomupdate);
            }
            GlobalNumbers.Instance.Dispose();

            Console.WriteLine($"Reservation til den {dato}, med personerne {childName}, {motherName} og {fatherName} er gennemført og gemt");
        }
        private async Task SyncShareHolders()
        {
            string familyDbPath = Properties.Settings.Default.FamilyDbPath;

            if (string.IsNullOrEmpty(familyDbPath))
            {
                string msg = Properties.Resources.SyncMembersView_FamilyDbMissing;
                Helper.ShowMessage(msg);
                return;
            }
            await Task.Run(() =>
            {
                var familyAppRepo = new Repository(familyDbPath);

                var familyAppMembers = familyAppRepo.GetShareHolders();
                var fbmRepo          = _unitOfWork.FamilyMembers;
                var fbmMembers       = fbmRepo.GetAll();
                int current          = 0;
                int count            = familyAppMembers.Count();
                foreach (FamilyMember familyMember in familyAppMembers)
                {
                    //bool exist = sgeCustomers.Any(cus => cus.CustomerId == irsCustomer.CustomerId);
                    bool exist = fbmMembers.Any(shHo => shHo.Code == familyMember.Code);
                    if (!exist)
                    {
                        var members = new FamilyMember
                        {
                            Code             = familyMember.Code,
                            Parent           = familyMember.Parent,
                            FirstName        = familyMember.FirstName,
                            FullName         = familyMember.FullName,
                            MotherCode       = familyMember.MotherCode,
                            Independent      = familyMember.Independent,
                            IndependentDate  = familyMember.IndependentDate,
                            Alive            = familyMember.Alive,
                            HasChildren      = familyMember.HasChildren,
                            Shares           = familyMember.Shares,
                            XShares          = familyMember.XShares,
                            Buffer           = familyMember.Buffer,
                            ShareHolderLevel = familyMember.ShareHolderLevel,
                            Sex = familyMember.Sex
                        };

                        fbmRepo.Add(members);
                    }
                    else
                    {
                        FamilyMember existingMember     = fbmMembers.Single(sh => sh.Code == familyMember.Code);
                        existingMember.Parent           = familyMember.Parent;
                        existingMember.FirstName        = familyMember.FirstName;
                        existingMember.FullName         = familyMember.FullName;
                        existingMember.MotherCode       = familyMember.MotherCode;
                        existingMember.Independent      = familyMember.Independent;
                        existingMember.IndependentDate  = familyMember.IndependentDate;
                        existingMember.Alive            = familyMember.Alive;
                        existingMember.HasChildren      = familyMember.HasChildren;
                        existingMember.Shares           = familyMember.Shares;
                        existingMember.XShares          = familyMember.XShares;
                        existingMember.Buffer           = familyMember.Buffer;
                        existingMember.ShareHolderLevel = familyMember.ShareHolderLevel;
                        existingMember.Sex = familyMember.Sex;
                    }
                    UpdateProgress(count, current);
                    current++;
                }
            });
        }
Exemple #5
0
 public WhosYour(FamilyMember familyMember)
 {
     Value = familyMember;
 }
Exemple #6
0
 public bool isExist(FamilyMember familyMember)
 {
     throw new NotImplementedException();
 }
Exemple #7
0
    // this only codifies the role-changing situation (bottom part)
    public static FamilyMember getRoleChangeMember(Family member, int table)
    {
        FamilyMember result = new FamilyMember();

        result.mood = Mood.sad;

        if (member == Family.son)
        {
            if (table == 0)
            {
                result.member = Family.parents;
                result.family = 1;
                return(result);
            }
            if (table == 2)
            {
                result.member = Family.daughter;
                result.family = 1;
                return(result);
            }
            if (table == 4)
            {
                result.member = Family.daughter;
                result.family = 2;
                return(result);
            }
            if (table == 5)
            {
                result.member = Family.son;
                result.family = 2;
                return(result);
            }

            // 'impossible' case, just to prevent the compiler from throwing an error
            return(result);
        }

        else if (member == Family.daughter)
        {
            if (table == 0)
            {
                result.member = Family.parents;
                result.family = 1;
                return(result);
            }
            if (table == 2)
            {
                result.member = Family.son;
                result.family = 1;
                return(result);
            }
            if (table == 4)
            {
                result.member = Family.son;
                result.family = 2;
                return(result);
            }
            if (table == 5)
            {
                result.member = Family.daughter;
                result.family = 2;
                return(result);
            }
            // 'impossible' case, just to prevent the compiler from throwing an error
            return(result);
        }

        else if (member == Family.father)
        {
            if (table == 1)
            {
                result.member = Family.siblings;
                result.family = 1;
                return(result);
            }
            if (table == 3)
            {
                result.member = Family.mother;
                result.family = 1;
                return(result);
            }
            if (table == 6)
            {
                result.member = Family.father;
                result.family = 2;
                return(result);
            }
            // 'impossible' case, just to prevent the compiler from throwing an error
            return(result);
        }

        else if (member == Family.mother)
        {
            if (table == 1)
            {
                result.member = Family.siblings;
                result.family = 1;
                return(result);
            }
            if (table == 3)
            {
                result.member = Family.father;
                result.family = 1;
                return(result);
            }
            if (table == 6)
            {
                result.member = Family.mother;
                result.family = 2;
                return(result);
            }

            // 'impossible' case, just to prevent the compiler from throwing an error
            return(result);
        }

        // 'impossible' case, just to prevent the compiler from throwing an error
        return(result);
    }
Exemple #8
0
 public FamilyMemberEditViewModel(int memberId) : this()
 {
     DisplayName     += memberId;
     PropertyChanged += OnFamilyMemberEditViewModelPropertyChanged;
     Model            = FamilyMember.GetFamilyMemberById(memberId);
 }
Exemple #9
0
        public static Boolean UploadAdults()
        {
            var db = new BHelpContext();

            var filePath = @"c:\TEMP\BH Food Client List-Table 1.csv";

            DataTable csvtable = new DataTable();

            using (CsvReader csvReader = new CsvReader(new StreamReader(filePath), true))
            { csvtable.Load(csvReader); }

            int i = 0;

            foreach (DataRow row in csvtable.Rows)
            {
                i++;                                 // Switch for  Kids / Adults:
                string _adults = row[10].ToString(); // Adults
                //string _adults = row[11].ToString();  // Kids
                string[] adultsArray = _adults.Split(',');
                foreach (var nameAge in adultsArray)
                {
                    if (i > 0)                                                                          // to reset if errors occured
                    {
                        if (nameAge.Contains(row[0].ToString()) && nameAge.Contains(row[1].ToString())) // First and Last Name))
                        {
                            //Don't add to FamilyMembers - just capture the age & update the client DoB
                            int ageIndex = nameAge.IndexOf('/');
                            if (ageIndex > 0)
                            {
                                var years = nameAge.Substring(nameAge.IndexOf('/') + 1);
                                //System.Diagnostics.Debug.WriteLine(i.ToString() + ' ' + row[0].ToString() + ' ' + row[1].ToString() + ' ' + years);

                                if (int.TryParse(years, out int yy))
                                {
                                    // Everybody born on April 1st
                                    DateTime doB      = new DateTime(2021 - yy, 4, 1);
                                    var      original = db.Clients.Find(i);
                                    if (original != null)
                                    {
                                        original.DateOfBirth = doB;
                                        db.SaveChanges();
                                    }
                                }
                            }
                        }
                        else // not a client - add a family member =================
                        {
                            string nameAgeTrim = nameAge.Trim();
                            var    years       = nameAge.Substring(nameAge.IndexOf('/') + 1);
                            if (int.TryParse(years, out int yy))
                            {
                                DateTime doB      = new DateTime(2021 - yy, 4, 1);
                                string   fullName = nameAgeTrim.Substring(0, nameAgeTrim.IndexOf('/'));
                                string   firstName;
                                string   lastName;
                                if (fullName.IndexOf(' ') <= 0)
                                {
                                    firstName = fullName;
                                    lastName  = "";
                                }
                                else
                                {
                                    firstName = fullName.Substring(0, fullName.IndexOf(' '));
                                    lastName  = fullName.Substring(fullName.IndexOf(' ') + 1);
                                }

                                FamilyMember newAdult = new FamilyMember()
                                {
                                    Active      = true,
                                    ClientId    = i,
                                    FirstName   = firstName,
                                    LastName    = lastName,
                                    DateOfBirth = doB
                                };
                                db.FamilyMembers.Add(newAdult);
                                db.SaveChanges();
                            }
                        }
                    }
                }
                //System.Diagnostics.Debug.WriteLine(client.FirstName, client.LastName);
            }
            return(true);
        }
        public void Show(Draw D, Rectangle Rect)
        {
            float Zoom       = 0.35f;
            int   Width      = 0;
            int   StartX     = Rect.X + Rect.Width / 2;
            int   dx         = 20;
            int   dy         = 75;
            bool  MouseOver  = false;
            int   Offset     = Common_Ancestor.Generation;
            int   FullHeight = (FamilyTree.Count + 2) * dy;
            int   Outside    = FullHeight - Rect.Height;
            int   Top        = dy - (int)(Outside * ScrollValue);

            for (int i = Offset; i < FamilyTree.Count + Offset; i++)
            {
                int FamId = i - Offset;
                int Y     = dy * (i - Offset) + Top;

                int NextY      = Y + dy;
                int NextWidth  = 0;
                int NextStartX = 0;
                int Nextdx     = 0;

                if (FamId + 1 < FamilyTree.Count)
                {
                    NextWidth  = (int)(Rect.Width * (1 - 5 / (FamilyTree[FamId + 1].Count + 4f)));
                    NextStartX = Rect.X + (Rect.Width - NextWidth) / 2;
                    if (FamilyTree[FamId + 1].Count > 1)
                    {
                        Nextdx = NextWidth / (FamilyTree[FamId + 1].Count - 1);
                    }
                    else
                    {
                        Nextdx = 0;
                    }
                }

                D.Graphics.DrawString(i.ToString(), D.Font, Brushes.Black, StartX - 50, Y, D.SF);

                for (int j = 0; j < FamilyTree[FamId].Count; j++)
                {
                    int          X             = StartX + j * dx;
                    FamilyMember Current       = FamilyTree[FamId][j];
                    bool         inHoverFamily = false;
                    if (HoverFamily != null && i - Offset < HoverFamily.Count)
                    {
                        inHoverFamily = HoverFamily[FamId].FamilyPos == j;
                    }
                    for (int k = 0; k < Current.Children.Count; k++)
                    {
                        int   X2            = NextStartX + Current.Children[k].FamilyPos * Nextdx;
                        int   Y2            = NextY;
                        Color Col           = Color.LightGray;
                        bool  HoverChildren = false;
                        if (inHoverFamily && i - Offset < HoverFamily.Count - 1)
                        {
                            if (HoverFamily[FamId + 1].FamilyPos == Current.Children[k].FamilyPos)
                            {
                                Col           = Color.Green;
                                HoverChildren = true;
                            }
                        }
                        D.Graphics.DrawLine(new Pen(Col, HoverChildren? 4:2), X, Y, X2, Y2);
                    }
                    if (!Current.Dead || inHoverFamily || Current.Selected)
                    {
                        float R   = CircleRadius * Zoom * 1.5f;
                        Color Col = Color.DarkOrange;
                        if (inHoverFamily)
                        {
                            Col = Color.Green;
                        }
                        if (Current.Selected)
                        {
                            D.Graphics.FillEllipse(Brushes.DarkGreen, X - R, Y - R, R * 2, R * 2);
                        }
                        else
                        {
                            D.Graphics.DrawEllipse(new Pen(Col, 2), X - R, Y - R, R * 2, R * 2);
                        }
                    }
                    //if (Current.IsEgg != null)
                    //{
                    //    Current.IsEgg.Show(D, X, Y, Zoom);
                    //}
                    //else
                    //{
                    Current.Show(D, X, Y, Zoom);
                    //}
                    if (Intersect(X, Y, CircleRadius * Zoom * 1.5f) && Current.Name.Length > 0)
                    {
                        Hover     = Current;
                        MouseOver = true;
                    }
                    D.Graphics.DrawString(Current.Name, D.Font, Brushes.Black, X, Y - CircleRadius * Zoom * 1.5f, D.SF);
                }
                Width  = NextWidth;
                StartX = NextStartX;
                dx     = Nextdx;
            }
            if (!MouseOver)
            {
                Hover       = null;
                HoverFamily = null;
            }
            else
            {
                HoverFamily = new List <FamilyMember>()
                {
                    Hover
                };
                int CurrentGen = Hover.Generation - Common_Ancestor.Generation;
                int CurrentPos = Hover.FamilyPos;
                while (CurrentGen > 0 && FamilyTree[CurrentGen][CurrentPos].Parents.Count > 0)
                {
                    CurrentPos = FamilyTree[CurrentGen][CurrentPos].Parents[0].FamilyPos;
                    CurrentGen--;
                    HoverFamily.Insert(0, FamilyTree[CurrentGen][CurrentPos]);
                }
                if (Form1.MouseHold)
                {
                    Draw.Selected = Hover;
                }
            }
            ShowScroll(D);
        }
        private void SaveChanges()
        {
            string userId = CurrentUser != null ? CurrentUser.Identity.Name : "PreRegistration";

            // Default Member Status
            Lookup memberStatus;

            try
            {
                memberStatus = new Lookup(Int32.Parse(MemberStatusIDSetting));
                if (memberStatus.LookupID == -1)
                {
                    throw new ModuleException(CurrentPortalPage, CurrentModule, "Member Status setting must be a valid Member Status Lookup value.");
                }
            }
            catch (System.Exception ex)
            {
                throw new ModuleException(CurrentPortalPage, CurrentModule, "Member Status setting must be a valid Member Status Lookup value.", ex);
            }

            // Default Campus
            int campusId = CampusSetting.Trim() != string.Empty ? int.Parse(CampusSetting) : -1;

            //if (Boolean.Parse(UseCampusPreferenceSetting) && CurrentArenaContext.CampusPreference != null)
            //    campusId = CurrentArenaContext.CampusPreference.CampusId;

            Arena.Organization.Campus campus = null;
            if (campusId != -1)
            {
                campus = new Arena.Organization.Campus(campusId);
            }

            FamilyMember you = _family.FamilyMembers.FindByGuid(new Guid(hfYouGuid.Value));

            if (_family.FamilyID == -1)
            {
                _family.OrganizationID = CurrentOrganization.OrganizationID;
                _family.FamilyName     = you.LastName.Trim() + " Family";
                _family.Save(userId);
            }

            foreach (FamilyMember fm in _family.FamilyMembers)
            {
                //*******Marital Status
                if (fm.PersonID == -1)
                {
                    fm.FamilyID       = _family.FamilyID;
                    fm.MemberStatus   = memberStatus;
                    fm.Campus         = campus;
                    fm.OrganizationID = CurrentOrganization.OrganizationID;
                }

                if (fm.PersonID != -1 || fm.NickName != string.Empty)
                {
                    if (fm.PersonGUID != you.PersonGUID)
                    {
                        PersonAddress homeAddress = fm.Addresses.FindByType(SystemLookup.AddressType_Home);
                        if (homeAddress == null)
                        {
                            homeAddress             = new PersonAddress();
                            homeAddress.AddressType = new Lookup(SystemLookup.AddressType_Home);
                            fm.Addresses.Add(homeAddress);
                            if (fm.Addresses.PrimaryAddress() == null)
                            {
                                homeAddress.Primary = true;
                            }
                        }
                        homeAddress.Address = you.Addresses.FindByType(SystemLookup.AddressType_Home).Address;

                        PersonPhone homePhone = fm.Phones.FindByType(SystemLookup.PhoneType_Home);
                        if (homePhone == null)
                        {
                            homePhone           = new PersonPhone();
                            homePhone.PhoneType = new Lookup(SystemLookup.PhoneType_Home);
                            fm.Phones.Add(homePhone);
                        }
                        homePhone.Number = you.Phones.FindByType(SystemLookup.PhoneType_Home).Number;
                    }


                    // Save Person
                    fm.Save(CurrentOrganization.OrganizationID, userId, false);
                    fm.SaveAddresses(CurrentOrganization.OrganizationID, userId);
                    fm.SavePhones(CurrentOrganization.OrganizationID, userId);
                    fm.SaveEmails(CurrentOrganization.OrganizationID, userId);
                    fm.Save(userId);

                    if (this.ProfileIDSetting != string.Empty)
                    {
                        AddToTag(fm);
                    }
                }
            }
        }
Exemple #12
0
        private int CalculatePointsThisWeek(FamilyMember familyMember)
        {
            var completedChoresThisWeek = familyMember.CompletedChores.Where(_ => _.DateEntered > DateTimeOffset.Now.AddDays(-7));

            return(completedChoresThisWeek.Sum(_ => _.PointsEarned));
        }
Exemple #13
0
        private int CalculatePointsThisMonth(FamilyMember familyMember)
        {
            var completedChoresThisWeek = familyMember.CompletedChores.Where(_ => _.DateEntered.Month == DateTimeOffset.Now.Month && _.DateEntered.Year == DateTimeOffset.Now.Year);

            return(completedChoresThisWeek.Sum(_ => _.PointsEarned));
        }
 public Calculator(FamilyMember familyMember)
 {
     FamilyMember = familyMember;
 }
    public void GlobalMoralUpdate(Transform barPanel, FamilyMember fm1, FamilyMember fm2, FamilyMember fm3, FamilyMember fm4)
    {
        float globalMoral = (fm1.moral + fm2.moral + fm3.moral + fm4.moral) / 4;

        BarUpdate(barPanel, globalMoral, 100);
    }
        /// <summary>
        /// Seeds the data without calling .SaveChanges
        /// </summary>
        public void Seed()
        {
            // Manager
            var managerPerson = new Person
            {
                Id        = 0,
                FirstName = "fn_manager",
                LastName  = "ln_manager",
                BirthDate = new DateTime(1969, 1, 3)
            };

            var managerWorker = new Worker
            {
                PersonId = managerPerson.Id,
                Person   = managerPerson,
                WorkTime = "9h - 17h",
                Role     = WorkerRoles.Manager
            };
            var manager = new Manager
            {
                WorkerId = managerWorker.PersonId,
                Worker   = managerWorker
            };

            // Tech staff
            var techStaffPerson = new Person
            {
                Id        = 1,
                FirstName = "fn_staff_member",
                LastName  = "ln_staff_member",
                BirthDate = new DateTime(1962, 5, 9)
            };

            var techStaffWorker = new Worker
            {
                PersonId = techStaffPerson.Id,
                Person   = techStaffPerson,
                WorkTime = "8h - 16h",
                Role     = WorkerRoles.TechnicalStaff
            };

            // Dead person
            var deadPerson = new Person
            {
                Id        = 2,
                BirthDate = new DateTime(1997, 4, 3),
                FirstName = "Danilo",
                LastName  = "Novakovic"
            };

            var deathRecord = new DeathRecord
            {
                PersonId  = deadPerson.Id,
                Person    = deadPerson,
                DeathDate = DateTime.Now
            };

            // Family
            var sisterPerson = new Person
            {
                Id        = 3,
                BirthDate = new DateTime(1999, 2, 6),
                FirstName = "Aleksandra",
                LastName  = "Novakovic"
            };

            var familyMember = new FamilyMember
            {
                Id           = sisterPerson.Id,
                MemberId     = sisterPerson.Id,
                Member       = sisterPerson,
                RelatedToId  = deathRecord.PersonId,
                RelatedTo    = deathRecord,
                RelationType = "sister"
            };

            // Chapel
            var chapelLocation = new Location
            {
                Id        = 0,
                Latitude  = 45.571988,
                Longitude = 19.668292,
            };

            var chapel = new Chapel
            {
                Id       = 0,
                Name     = "White Chapel",
                Location = chapelLocation
            };

            // Contracts
            var contract = new Contract
            {
                Id               = 0,
                Manager          = manager,
                FamilyMember     = familyMember,
                FuneralStartTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, 14, 00, 00),
                FuneralType      = FuneralType.Burial,
                Chapel           = chapel
            };

            var graveSiteLocation = new Location
            {
                Id        = 1,
                Latitude  = 45.572393,
                Longitude = 19.667079
            };

            var graveSite = new GraveSite
            {
                DeathRecordId = 0,
                DeathRecord   = deathRecord,
                Location      = graveSiteLocation,
                Type          = GraveSiteType.Coffin
            };

            var coffin = new Coffin
            {
                GraveSiteId = graveSite.DeathRecordId,
                GraveSite   = graveSite,
                Mark        = "Black Coffin v1.0 - Smooth Edition"
            };

            _context.Locations.AddOrUpdate(chapelLocation, graveSiteLocation);
            _context.Chapels.AddOrUpdate(chapel);

            _context.Persons.AddOrUpdate(managerPerson, techStaffPerson, deadPerson, sisterPerson);

            _context.DeathRecords.AddOrUpdate(deathRecord);
            _context.GraveSites.AddOrUpdate(graveSite);
            _context.Coffins.AddOrUpdate(coffin);

            _context.FamilyMembers.AddOrUpdate(familyMember);

            _context.Workers.AddOrUpdate(managerWorker, techStaffWorker);
            _context.Managers.AddOrUpdate(manager);
            _context.TechnicalStaff.AddOrUpdate(new TechnicalStaff
            {
                WorkerId  = techStaffWorker.PersonId,
                ManagerId = manager.WorkerId
            });

            _context.Contracts.AddOrUpdate(contract);
        }
        /// <summary>
        /// Aproves the stock purchase.
        /// </summary>
        /// <param name="adminMember">Admin member</param>
        /// <param name="pendingStockRequestId">Pending stock request identifier.</param>
        /// <returns></returns>
        public async Task ApproveStockPurchase(FamilyMember adminMember, int pendingStockRequestId)
        {
            var pendingStockRequest = Repository.Table <StockPurchaseRequest>()
                                      .Include(p => p.Child)
                                      .Include(p => p.StockItem)
                                      .SingleOrDefault(p => p.Id == pendingStockRequestId);

            // Prepare stock purchase request data
            var purchaser = new Purchaser
            {
                Email = adminMember.User.Email,
                //Email = "*****@*****.**",
                FirstName = adminMember.Firstname,
                LastName  = adminMember.Lastname,
            };

            var recipient = new Purchaser
            {
                Email = adminMember.User.Email,
                //Email = "*****@*****.**",
                FirstName = adminMember.Firstname,
                LastName  = adminMember.Lastname,
            };

            var stockData = new PurchaseStockRequest
            {
                Preamble = new Preamble
                {
                    TransactionID  = pendingStockRequest.TransactionID,
                    InstitutionID  = _institutionId,
                    PartnerProgram = "RewardPointsToStock"
                },
                Purchaser      = purchaser,
                PaymentDetails = new PaymentDetails
                {
                    PaymentType = "PREFUNDED"
                },
                PrepaidValueItemRequests = new List <PrepaidValueItemRequest>()
                {
                    new PrepaidValueItemRequest {
                        ItemCode       = pendingStockRequest.StockItem.ItemCode,
                        ItemType       = "SECURITY",
                        DeliveryOption = "EMAIL",
                        CurrencyCode   = "USD",
                        Value          = pendingStockRequest.Amount,
                        LineItemID     = pendingStockRequest.LineItemID,
                        Recipient      = recipient
                    }
                }
            };

            try
            {
                if (!pendingStockRequest.BankTransactionID.HasValue)
                {
                    if (!_bankService.IsBankLinked(adminMember.Id))
                    {
                        throw new InvalidOperationException("Bank is not linked or verified!");
                    }

                    var stockAmount = pendingStockRequest.Amount + pendingStockRequest.Fee; // Transferring stock amount including Fee

                    // Tranfer amount from customer account to program account
                    var transactionResult = _transactionService.Transfer(adminMember.Id, stockAmount, PaymentType.StockPile, TransferType.InternalToBusyKidInternalAccount);

                    if (!transactionResult.HasValue)
                    {
                        throw new InvalidOperationException("Unable to process the transaction. Please contact bank or mail to us!");
                    }

                    // Update pending stock request
                    pendingStockRequest.BankTransactionID = transactionResult;
                    Repository.Update(pendingStockRequest);
                }

                // Purchase the stock.
                var stockPurchaseResponse = await _stockPileService.PurchaseStock(stockData);

                // Make order request
                var orderResponse = await _stockPileService.Order(stockPurchaseResponse.Preamble.TransactionID.ToString());

                // Update the stock purchase request
                pendingStockRequest.Status = ApprovalStatus.Completed;
                Repository.Update(pendingStockRequest);

                // send a custom stock purchase email
            }
            catch (Exception ex)
            {
                var stockAmount = pendingStockRequest.Amount + pendingStockRequest.Fee; // Transferring stock amount including Fee
                _transactionService.SaveTransactionLog(adminMember.Id, ex.Message, stockAmount);
                throw ex;
            }
        }
 public IEnumerable <FamilyMember> AddMember(FamilyMember newMember)
 {
     dbSet.Add(newMember);
     _context.SaveChanges();
     return(dbSet);
 }
        private void UpdateChanges()
        {
            if (pnlYou.Visible)
            {
                FamilyMember fm = _family.FamilyMembers.FindByGuid(new Guid(hfYouGuid.Value));
                if (fm != null)
                {
                    fm.NickName = tbYouFirstName.Text;
                    fm.LastName = tbYouLastName.Text;

                    PersonAddress homeAddress = fm.Addresses.FindByType(SystemLookup.AddressType_Home);
                    if (homeAddress == null)
                    {
                        homeAddress             = new PersonAddress();
                        homeAddress.AddressType = new Lookup(SystemLookup.AddressType_Home);
                        homeAddress.Address     = new Address();

                        if (fm.PrimaryAddress == null)
                        {
                            homeAddress.Primary = true;
                        }

                        fm.Addresses.Add(homeAddress);
                    }

                    homeAddress.Address.StreetLine1 = tbAddress.Text;
                    homeAddress.Address.City        = tbCity.Text;
                    homeAddress.Address.State       = tbState.Text;
                    homeAddress.Address.PostalCode  = tbZip.Text;

                    PersonPhone homePhone = fm.Phones.FindByType(SystemLookup.PhoneType_Home);
                    if (homePhone == null)
                    {
                        homePhone           = new PersonPhone();
                        homePhone.PhoneType = new Lookup(SystemLookup.PhoneType_Home);
                        fm.Phones.Add(homePhone);
                    }
                    homePhone.Number = ptbYouHomeNum.PhoneNumber;

                    fm.BirthDate = dtYouBirthDate.SelectedDate;

                    if (ddlYouGender.SelectedValue == "Male")
                    {
                        fm.Gender = Arena.Enums.Gender.Male;
                    }
                    else if (ddlYouGender.SelectedValue == "Female")
                    {
                        fm.Gender = Arena.Enums.Gender.Female;
                    }
                    else
                    {
                        fm.Gender = Arena.Enums.Gender.Unknown;
                    }
                }
            }

            if (pnlSpouse.Visible)
            {
                FamilyMember fm = _family.FamilyMembers.FindByGuid(new Guid(hfSpouseGuid.Value));
                if (fm != null)
                {
                    fm.NickName = tbSpouseFirstName.Text;
                    fm.LastName = tbSpouseLastName.Text;

                    fm.BirthDate = dtSpouseBirthDate.SelectedDate;

                    FamilyMember spouse = _family.Spouse(fm);
                    if (spouse != null)
                    {
                        if (spouse.Gender == Arena.Enums.Gender.Male)
                        {
                            fm.Gender = Arena.Enums.Gender.Female;
                        }
                        else if (spouse.Gender == Arena.Enums.Gender.Female)
                        {
                            fm.Gender = Arena.Enums.Gender.Male;
                        }
                    }
                }
            }

            if (pnlFamilyMembers.Visible)
            {
                foreach (ListViewDataItem item in lvFamilyMembers.Items)
                {
                    HiddenField  hfPersonGuid = (HiddenField)item.FindControl("hfPersonGuid");
                    FamilyMember fm           = _family.FamilyMembers.FindByGuid(new Guid(hfPersonGuid.Value));

                    fm.NickName  = ((TextBox)item.FindControl("tbFirstName")).Text;
                    fm.LastName  = ((TextBox)item.FindControl("tbLastName")).Text;
                    fm.BirthDate = ((DateTextBox)item.FindControl("dtbBirthDate")).SelectedDate;

                    string gender = ((DropDownList)item.FindControl("ddlGender")).SelectedValue;
                    switch (gender)
                    {
                    case "Male": fm.Gender = Arena.Enums.Gender.Male; break;

                    case "Female": fm.Gender = Arena.Enums.Gender.Female; break;

                    default: fm.Gender = Arena.Enums.Gender.Unknown; break;
                    }

                    int grade = Convert.ToInt32(((DropDownList)item.FindControl("ddlGrade")).SelectedValue);
                    fm.GraduationDate = Person.CalculateGraduationYear(grade, CurrentOrganization.GradePromotionDate);
                }
            }

            if (pnlContactInfo.Visible)
            {
                foreach (ListViewDataItem item in lvEmailCell.Items)
                {
                    HiddenField  hfPersonGuid = (HiddenField)item.FindControl("hfPersonGuid");
                    FamilyMember fm           = _family.FamilyMembers.FindByGuid(new Guid(hfPersonGuid.Value));
                    fm.Emails.FirstActive = ((TextBox)item.FindControl("tbEmail")).Text;

                    PersonPhone  cellPhone  = fm.Phones.FindByType(SystemLookup.PhoneType_Cell);
                    PhoneTextBox ptbCellNum = ((PhoneTextBox)item.FindControl("ptbCellNum"));
                    if (cellPhone == null && ptbCellNum.PhoneNumber.Trim() != string.Empty)
                    {
                        cellPhone           = new PersonPhone();
                        cellPhone.PhoneType = new Lookup(SystemLookup.PhoneType_Cell);
                        fm.Phones.Add(cellPhone);
                    }
                    if (cellPhone != null)
                    {
                        cellPhone.Number = ptbCellNum.PhoneNumber;
                    }
                }
            }
        }
        private void Register_Click(object sender, EventArgs e)
        {
            if (state != ihState.Value)
            {
                // NOTE: If this is invalid, something's not right with the Facebook session...
                //lblSignupError.Text = "Oops, something wonky happened. Please reload the page and ";
                //lblSignupError.Visible = true;
                return;
            }

            try
            {
                var facebookUser = GetFacebookUser();
                var id = facebookUser["id"].ToString();

                string password = string.Empty;
                var person = PopulatePerson(facebookUser, CREATED_BY);
                person.Save(CurrentOrganization.OrganizationID, CREATED_BY, true);

                // Thanks again Arena!
                var family = new Family
                                 {
                                     OrganizationID = CurrentOrganization.OrganizationID,
                                     FamilyName = string.Format("{0} Family", person.LastName)
                                 };
                family.Save(CREATED_BY);
                var familyMember = new FamilyMember(family.FamilyID, person.PersonID)
                                       {
                                           FamilyID = family.FamilyID,
                                           FamilyRole = new Lookup(SystemLookup.FamilyRole_Adult)
                                       };
                familyMember.Save(CREATED_BY);

                // Thanks Arena!
                var trash = person.Logins;
                var loginID = person.AddLogin(true, CREATED_BY, out password);

                // Add a PersonAttribute to their record with their Facebook ID.
                SavePersonAttribute(person, id, CurrentOrganization.OrganizationID);
                FormsAuthentication.SetAuthCookie(loginID, false);
                Response.Cookies["portalroles"].Value = string.Empty;
                Redirect();
            }
            catch (System.Exception ex)
            {
                new ExceptionHistoryData().AddUpdate_Exception(ex, CurrentOrganization.OrganizationID,
                    "Cccev.Web", ArenaContext.Current.ServerUrl);
            }
        }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (_family == null)
            {
                FamilyMember you    = null;
                FamilyMember spouse = null;

                if (CurrentPerson != null)
                {
                    _family = CurrentPerson.Family();

                    you = _family.FamilyMembers.FindByGuid(CurrentPerson.PersonGUID);

                    spouse = _family.Spouse(CurrentPerson);
                }
                else
                {
                    _family = new Family();

                    you            = new FamilyMember();
                    you.PersonGUID = Guid.NewGuid();
                    you.FamilyRole = new Lookup(SystemLookup.FamilyRole_Adult);
                    you.Gender     = Arena.Enums.Gender.Unknown;
                    _family.FamilyMembers.Add(you);
                }

                // Save Spouse
                if (spouse == null)
                {
                    spouse            = new FamilyMember();
                    spouse.PersonGUID = Guid.NewGuid();
                    spouse.FamilyRole = new Lookup(SystemLookup.FamilyRole_Adult);
                    if (CurrentPerson != null && CurrentPerson.Gender == Arena.Enums.Gender.Male)
                    {
                        you.Gender = Arena.Enums.Gender.Female;
                    }
                    else if (CurrentPerson != null && CurrentPerson.Gender == Arena.Enums.Gender.Female)
                    {
                        you.Gender = Arena.Enums.Gender.Male;
                    }
                    else
                    {
                        you.Gender = Arena.Enums.Gender.Unknown;
                    }
                    _family.FamilyMembers.Add(spouse);
                }

                // Save Guids
                hfYouGuid.Value    = you.PersonGUID.ToString();
                hfSpouseGuid.Value = spouse.PersonGUID.ToString();
            }

            if (Page.IsPostBack)
            {
                UpdateChanges();
            }
            else
            {
                ShowYou();
            }
        }
Exemple #22
0
        public List <FamilyMember> GetFamilyMembersNewerThen(int companyId, DateTime lastUpdateTime)
        {
            List <FamilyMember> FamilyMembers = new List <FamilyMember>();

            string queryString =
                "SELECT FamilyMemberId, FamilyMemberIdentifier, FamilyMemberCode, FamilyMemberName, " +
                "Active, UpdatedAt, CreatedById, CreatedByFirstName, CreatedByLastName, CompanyId, CompanyName " +
                "FROM vFamilyMembers " +
                "WHERE CompanyId = @CompanyId " +
                "AND CONVERT(DATETIME, CONVERT(VARCHAR(20), UpdatedAt, 120)) > CONVERT(DATETIME, CONVERT(VARCHAR(20), @LastUpdateTime, 120));";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = queryString;
                command.Parameters.Add(new SqlParameter("@CompanyId", companyId));
                command.Parameters.Add(new SqlParameter("@LastUpdateTime", lastUpdateTime));

                connection.Open();
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    FamilyMember familyMember;
                    while (reader.Read())
                    {
                        familyMember            = new FamilyMember();
                        familyMember.Id         = Int32.Parse(reader["FamilyMemberId"].ToString());
                        familyMember.Identifier = Guid.Parse(reader["FamilyMemberIdentifier"].ToString());
                        familyMember.Code       = reader["FamilyMemberCode"].ToString();
                        familyMember.Name       = reader["FamilyMemberName"].ToString();

                        familyMember.Active    = bool.Parse(reader["Active"].ToString());
                        familyMember.UpdatedAt = DateTime.Parse(reader["UpdatedAt"].ToString());

                        if (reader["CreatedById"] != DBNull.Value)
                        {
                            familyMember.CreatedBy           = new User();
                            familyMember.CreatedById         = Int32.Parse(reader["CreatedById"].ToString());
                            familyMember.CreatedBy.Id        = Int32.Parse(reader["CreatedById"].ToString());
                            familyMember.CreatedBy.FirstName = reader["CreatedByFirstName"]?.ToString();
                            familyMember.CreatedBy.LastName  = reader["CreatedByLastName"]?.ToString();
                        }

                        if (reader["CompanyId"] != DBNull.Value)
                        {
                            familyMember.Company      = new Company();
                            familyMember.CompanyId    = Int32.Parse(reader["CompanyId"].ToString());
                            familyMember.Company.Id   = Int32.Parse(reader["CompanyId"].ToString());
                            familyMember.Company.Name = reader["CompanyName"].ToString();
                        }

                        FamilyMembers.Add(familyMember);
                    }
                }
            }
            return(FamilyMembers);

            //List<FamilyMember> cities = context.FamilyMembers
            //    .Include(x => x.Company)
            //    .Include(x => x.CreatedBy)
            //    .Where(x => x.Company.Id == companyId && x.UpdatedAt > lastUpdateTime)
            //    .OrderByDescending(x => x.UpdatedAt)
            //    .AsNoTracking()
            //    .ToList();

            //return cities;
        }
 public async Task <FamilyMember> UpdateAsync(FamilyMember entity)
 {
     return(await unitOfWork.FamilyMembers.UpdateAsync(entity));
 }
    void Update()
    {
        if (state == 0)           // idling

        {
        }

        if (state == 1)
        {
            sit = situationChooser.chooseSituation(gameController.currentPlayerRole, tType, 0);

            if (situationChooser.isNegativeSituation(sit.table, sit.row))
            {
                sitNegative = true;
            }
            else
            {
                sitNegative = false;
            }

            destFamilyMember        = new FamilyMember();
            destFamilyMember.member = gameController.currentPlayerRole;
            destFamilyMember.family = 1;
            destFamilyMember.mood   = Mood.happy;



            iReturnValue = MoodInteger.enumToInt(sit.mood);             // mood set from situation. Overriden by test type 2
            // iReturnValue holds MOOD

            if (tType == GameController.Type0Test)
            {
                type0Test.SetActive(true);
                type0TestController.startType0Test(this);
                state = 2;                 // wait for this to finish
            }
            if (tType == GameController.Type1Test)
            {
                type1Test.SetActive(true);
                type1TestController.startType1Test(this);
                destFamilyMember.mood = Mood.thoughtful;
                state = 2;                 // wait for this to finish
            }
            if (tType == GameController.Type2Test)
            {
                type2Test.SetActive(true);
                type2TestController.startType2Test(this, sit);
                state = 2;                 // wait for this to finish
            }
            if (tType == GameController.Type3Test)
            {
                type3Test.SetActive(true);
                type3TestController.startType3Test(this);
                destFamilyMember.mood = Mood.assertive;
                state = 2;                 // wait for this to finish
            }
            if (tType == GameController.Type4Test)
            {
                type4Test.SetActive(true);
                type4TestController.startType4Test(this);
                destFamilyMember.mood = Mood.sad;
                state = 2;                                // wait for this to finish
            }
            if (tType == GameController.AllPlaySituation) // this type is only for notMyTurn's
            {
                helpPanelScaler.scaleOutImmediately();
                helpButtonScaler.scaleOutImmediately();
                helpButtonScaler.scaleIn();
                helpPanelMediationScaler.scaleOutImmediately();
                helpMediationButtonScaler.scaleOutImmediately();
                test.SetActive(true);
                faderText.fadeIn();
                tType = 3;                 // tType is actually 3
                bool NS = situationChooser.isNegativeSituation(sitTable, sitRow);
                updateInterrogationText(NS, 2);
                miniatureController.updateMiniature(3, sitTable, NS, sitRow);
                state = 40;
            }
        }

        if (state == 2)           // waiting for header to finish
        {
            if (!isWaitingForTaskToComplete)
            {
                //if (tType > 0) {
                if (!situationChooser.isNegativeSituation(sit.table, sit.row))
                {
                    destFamilyMember.mood = Mood.happy;
                }
                //}
                type0Test.SetActive(false);
                type1Test.SetActive(false);
                type2Test.SetActive(false);
                type3Test.SetActive(false);
                type4Test.SetActive(false);
                helpPanelScaler.scaleOutImmediately();
                helpButtonScaler.scaleOutImmediately();
                helpButtonScaler.scaleIn();
                helpPanelMediationScaler.scaleOutImmediately();
                helpMediationButtonScaler.scaleOutImmediately();
                test.SetActive(true);
                //if (tType > 0) {
                miniatureController.updateMiniature(tType, sit.table, situationChooser.isNegativeSituation(sit.table, sit.row), sit.row);
                //} else {
                //miniatureController.updateMiniature (tType, sit.table, true);
                //}
                int extraValue;
                if (tType == 2)
                {
                    extraValue = iReturnValue;
                }
                else
                {
                    extraValue = FamilyInteger.enumToInt(gameController.currentPlayerRole);
                }

                gameController.table  = sit.table;
                gameController.tType  = tType;
                gameController.family = destFamilyMember.family;
                gameController.mood   = destFamilyMember.mood;
                gameController.member = destFamilyMember.member;

                if (tType > 0)
                {
                    gameController.isNegative = situationChooser.isNegativeSituation(sit.table, sit.row);
                }

                // GOTO 3: NORMAL SITUATION
                // GOTO 30: SPECIAL K

                // Aquí vamos a decidir si se trata de una situación speciak K o no
                //bool isNegativeSituation = false;
                bool isAllPlaySituation = false;

                subType = 0;

                // if tType == 3 a new situation is chosen!!
                if (tType == 3)                   // only in test #3 we can have the possibility of a neg. situation
                // subType is sittin in iReturnValue
                {
                    subType = iReturnValue;
                    Debug.Log("<color=blue>Subtype via iReturnValue</color> : " + subType);

                    isAllPlaySituation = (subType == 2);
                    sit = situationChooser.chooseSituation(gameController.currentPlayerRole, tType, subType);
                    while (!situationChooser.isNegativeSituation(sit.table, sit.row))                        // theoretically, this forces the situation to be negative
                    {
                        sit = situationChooser.chooseSituation(gameController.currentPlayerRole, tType, subType);
                    }
                    miniatureController.updateMiniature(3, sit.table, situationChooser.isNegativeSituation(sit.table, sit.row), sit.row);
                    testText.text = sit.question;

                    //isNegativeSituation = situationChooser.isNegativeSituation (sit.table, sit.row);
                }

                //gameController.networkAgent.broadcast ("setanswers:" +
                //	sit.table + ":" +
                //		sit.row + ":" +
                //		sit.qc + ":" +
                //		sit.a1c + ":" +
                //		sit.a2c + ":" +
                //		FamilyInteger.enumToInt(destFamilyMember.member) + ":" +
                //		destFamilyMember.family + ":" +
                //		MoodInteger.enumToInt(destFamilyMember.mood) + ":" +
                //		subType + ":");
                testText.text = sit.question;
                notMyRouletteController.setAnswerText(sit.table, sit.row, sit.qc,
                                                      sit.a1c, sit.a2c, FamilyInteger.enumToInt(destFamilyMember.member), destFamilyMember.family, MoodInteger.enumToInt(destFamilyMember.mood), subType);

                faderText.fadeIn();

                PSHelpStrings.rosetta = rosetta.rosetta;
                NSHelpStrings.rosetta = rosetta.rosetta;
                bool localNS = situationChooser.isNegativeSituation(sit.table, sit.row);
                updateInterrogationText(localNS, subType);
                // HERE we know type, subtype (iReturnValue) and ns. Set help text...
                //helpPanelText.text

                if (subType == 1)
                {
                    helpPanelMediationScaler.scaleOutImmediately();
                    helpMediationButtonScaler.scaleOutImmediately();
                    helpMediationButtonScaler.scaleIn();
                }

                if (isAllPlaySituation == true)                   // a all play situation, special mechanics
                // tell other players to show test screen
                {
                    helpButton.enabled = true;
                    //gameController.networkAgent.broadcast("allplaysituation:" + sit.table + ":" + sit.row + ":");
                    state = 30;                     // wait for OK button to be hit (alt)
                }

                else                   // a single play situation, usual mechanics
                {
                    state = 3;         // wait for test.OK button to be hit
                }
            }
        }

        if (state == 3)           // waiting for test.OK button to be hit

        {
        }


        // HABRIA QUE COPIAR ESTE ESTADO ENTERO DANDOLE EL VALOR PREDETERMINADO DE 10 (AL DEL TURNO) LOS DEMAS SYNC
        if (state == 600)          // type0: waiting for fadeout after OK was hit
        {
            if (!isWaitingForTaskToComplete)
            {
                test.SetActive(false);

                nubarronActivity.SetActive(true);
                if (tType == 2 || tType == 4)
                {
                    nubarronController.startNubeActivity(this, 2);
                }
                else
                {
                    nubarronController.startNubeActivity(this, 1);
                }
                //faderMask.fadeIn ();
                state = 601;
            }
        }
        // HABRIA QUE COPIAR ESTE ESTADO ENTERO DANDOLE EL VALOR PREDETERMINADO DE 10 (AL DEL TURNO) LOS DEMAS SYNC
        if (state == 700)          // type0: waiting for fadeout after OK was hit
        {
            if (!isWaitingForTaskToComplete)
            {
                test.SetActive(false);
                test.SetActive(false);
                nubarronActivity.SetActive(true);
                nubarronController.startNubeActivity(this, 0);
                state = 601;
            }
        }
        if (state == 601)           // wait for nube activity to finish (will finish when votations arrive)
        {
            if (!isWaitingForTaskToComplete)
            {
                nubarronActivity.SetActive(false);
                AdvanceText.text = "Avanza 10 casillas";
                circleAdvance.SetActive(false);
                advanceCanvas.SetActive(true);
                faderAdvance.fadeIn();
                state = 62;
            }
        }
        if (state == 60)          // type0: waiting for fadeout after OK was hit
        {
            if (!isWaitingForTaskToComplete)
            {
                test.SetActive(false);
                nubarronActivity.SetActive(true);
                nubarronController.startNubeActivity(this, 0);
                state = 61;
            }
        }
        if (state == 61)           // wait for nube activity to finish (will finish when votations arrive)
        {
            if (!isWaitingForTaskToComplete)
            {
                nubarronActivity.SetActive(false);

                int nCasillas = (int)Mathf.Floor(fReturnValue);
                if (nCasillas != 1)
                {
                    AdvanceText.text = "Avanza " +
                                       nCasillas +
                                       " casillas";
                }
                else
                {
                    AdvanceText.text = "Avanza 1 casilla";
                }
                circleAdvance.SetActive(true);
                advanceCanvas.SetActive(true);
                faderAdvance.fadeIn();
                state = 62;
            }
        }
        if (state == 62)           // wait for ok button to be pressed

        {
        }
        if (state == 63)
        {
            faderAdvance.fadeOutTask(this);
            state = 64;
        }
        if (state == 64)           // waiting for fadeout
        {
            if (!isWaitingForTaskToComplete)
            {
                test.SetActive(false);
                advanceCanvas.SetActive(false);
                state = 0;
                notifyFinishTask();
            }
        }



        if (state == 4)           // type1, 2, 3, 4.. waiting for fadeout after OK was hit
        {
            if (!isWaitingForTaskToComplete)
            {
                test.SetActive(false);
                nubarronActivity.SetActive(true);
                if (tType == 2 || tType == 4)
                {
                    nubarronController.startNubeActivity(this, 2);
                }
                else
                {
                    nubarronController.startNubeActivity(this, 1);
                }
                //faderMask.fadeIn ();
                state = 5;
            }
        }

        if (state == 5)           // wait for nubarron activity to finish
        {
            if (!isWaitingForTaskToComplete)
            {
                //faderMask.fadeOutTask (this);
                nubarronActivity.SetActive(false);
                notifyFinishTask();
                state = 0;
            }
        }

        /*
         * if(state == 6) { // waiting for fadeout
         *      if(!isWaitingForTaskToComplete) {
         *              //mask.SetActive(false);
         *              state = 0;
         *              notifyFinishTask(); // return to parent task
         *      }
         * }
         */


        if (gameController.isMaster)           // only the master must execute slot 2
        {
            if (state2 == 0)
            {
            }              // idle
            if (state2 == 1)
            {
                // clear array used for marking chosen players (do not choose same player twice!)
                for (int i = 0; i < GameController.MaxPlayers; ++i)
                {
                    negativeSituationChosenPlayers [i] = false;
                }

                // prepare randomized attitude array (last item must be assertive (3 o MaxPlayers-1)!)
                randomAttitude = new List <int>();
                for (int i = 0; i < gameController.nPlayers - 1; ++i)
                {
                    int r = Random.Range(0, GameController.MaxPlayers - 1);
                    while (randomAttitude.Contains(r))
                    {
                        r = Random.Range(0, GameController.MaxPlayers - 1);
                    }
                    randomAttitude.Add(r);
                }
                randomAttitude.Add(GameController.MaxPlayers - 1);                  // there's really no need to, but for extra consistency...


                negativeSituationPickedPlayers = 0;

                state2 = 3;
            }
            if (state2 == 3)
            {
                // the master chooses a player

                if (negativeSituationPickedPlayers < gameController.nPlayers - 1)
                {
                    // choose a suitable player at random
                    chosenPlayer = Random.Range(0, GameController.MaxPlayers);
                    while ((chosenPlayer == gameController.playerTurn) || (negativeSituationChosenPlayers[chosenPlayer] == true) ||
                           (gameController.playerPresent[chosenPlayer] == false))
                    {
                        chosenPlayer = Random.Range(0, GameController.MaxPlayers);
                    }
                    negativeSituationChosenPlayers [chosenPlayer] = true;
                    ++negativeSituationPickedPlayers;
                    state2 = 4;                     // start mask on notMyTurn
                }

                else
                {
                    chosenPlayer = gameController.playerTurn;
                    state2       = 10;               // start mask on myTurn
                }
            }
            if (state2 == 4)
            {
                // command player to do the mask thing
                //gameController.networkAgent.sendCommand(gameController.playerList[chosenPlayer].id, "nsmask:" + randomAttitude[negativeSituationPickedPlayers-1] + ":");
                state2 = 5;
            }
            if (state2 == 5)               // wait until nmt presses mask.OK button

            {
            }
            if (state2 == 6)               // OK button pressed, to next player
            {
                state2 = 3;                // loop back and choose next player
            }
            if (state2 == 10)              // command turn player to do the mask thing
            //gameController.networkAgent.sendCommand(gameController.playerList[gameController.playerTurn].id, "nsmask:" + (GameController.MaxPlayers-1) + ":");
            {
                votedPlayers = 0;
                state2       = 11;
            }
            if (state2 == 11)               // wait until remote mt presses mask.OK button
            {
            }

            if (state2 == 12)              // tell everybody to vote attitude # <votedPlayers>
            {
                timer2 = 0.0f;
                state2 = 13;
                //if (votedPlayers == gameController.nPlayers - 1) {
                //	// GameController.MaxPlayers - 1  is the  'Assertive'  one
                //	//gameController.networkAgent.broadcast ("nsvote:" + (GameController.MaxPlayers - 1) + ":");
                //	voteNS((GameController.MaxPlayers - 1));
                //} else {
                //	//gameController.networkAgent.broadcast ("nsvote:" + votedPlayers + ":");
                //	voteNS (votedPlayers);
                //}
                //state2 = 13;
            }
            if (state2 == 13)               // waiting for notMyRoulette votation to finish
            {
                timer2 += Time.deltaTime;
                if (timer2 > 0.5f)
                {
                    timer2 = 0.0f;
                    state2 = 15;
                }
                //if (!isWaitingForTaskToComplete) {
                //	state2 = 14;
                //}
            }
            if (state2 == 14)
            {
                //++votedPlayers;
                //if (votedPlayers == gameController.nPlayers) {
                //	state2 = 15; // everybody voted
                //} else {
                //	state2 = 12; // loop back to tell everybody to vote #...
                //}
            }
            if (state2 == 15)
            {
                finishNS();
                //gameController.networkAgent.broadcast ("finishns:");
            }
        }



        if (state == 30)           // negativesituation, myturn, wait for OK

        {
        }
        if (state == 31)
        {
            if (!isWaitingForTaskToComplete)
            {
                syncCanvas.SetActive(true);
                //gameController.networkAgent.broadcast ("synch:");
                state = 32;
            }
        }
        if (state == 32)           // wait for synch
        {
            if (gameController.synchNumber >= gameController.nPlayers - 1)
            {
                gameController.synchNumber = 0;
                syncCanvas.SetActive(false);
                //state = 32;
                state = 80;
            }
        }
        //		if (state == 32) {
        //			if(gameController.isMaster) state2 = 1; // start master slot
        //			state = 33;
        //		}
        //		if (state == 33) { // wait until instructed to show mask
        //
        //		}



        if (state == 40)           // negativesituation, notMyTurn, wait for test.OK

        {
        }
        if (state == 41)
        {
            if (!isWaitingForTaskToComplete)
            {
                syncCanvas.SetActive(true);
                //gameController.networkAgent.broadcast ("synch:");
                state = 42;
            }
        }
        if (state == 42)           // wait for synch
        {
            if (gameController.synchNumber >= gameController.nPlayers - 1)
            {
                gameController.synchNumber = 0;
                syncCanvas.SetActive(false);
                //state = 42;
                state = 80;
            }
        }

        //		if (state == 42) {
        //			if(gameController.isMaster) state2 = 1; // start master slot
        //			state = 43;
        //		}
        //		if (state == 43) {
        //
        //
        //
        //			// slaves wait to be summoned, as the likes of 'em scum deserve!
        //
        //
        //
        //
        //		}
        //		if (state == 44) { // start mask on notMyTurn
        //
        //		}


        if (state == 80)
        {
            test.SetActive(false);
            type3Aux.SetActive(true);
            syncCanvas.SetActive(false);
            type3AuxController.startType3Aux(this);
            state = 81;
        }
        if (state == 81)           // wait until test3aux finishes
        {
            if (!isWaitingForTaskToComplete)
            {
                finishNS();
            }
        }
    }
Exemple #25
0
 public void Update(FamilyMember familyMember)
 {
     throw new NotImplementedException();
 }
Exemple #26
0
 public SavingsCalculator(FamilyMember familyMember)
 {
     _familyMember = familyMember;
 }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Charset     = "utf-8";
            HttpPostedFile file = context.Request.Files["Filedata"];

            if (file != null)
            {
                string AreaId        = context.Request.Form["AreaId"];
                string retFailInfo   = "";
                int    relationOfMan = 99999;
                int    count         = 0;

                IList <StringObjectDictionary> datas      = NPOIManager.GetSheetData(file.InputStream, 0, true);
                List <IBatisNetBatchStatement> statements = new List <IBatisNetBatchStatement>();
                List <IBatisNetBatchStatement> oldmanconfig_statements = new List <IBatisNetBatchStatement>();
                List <IBatisNetBatchStatement> familymember_statements = new List <IBatisNetBatchStatement>();
                List <IBatisNetBatchStatement> oldmanfamily_statements = new List <IBatisNetBatchStatement>();

                //获取图片
                //NPOI.HSSF.UserModel.HSSFWorkbook hssfworkbook = new NPOI.HSSF.UserModel.HSSFWorkbook(file.InputStream);
                //NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
                //Dictionary<string, Byte[]> picDataDictionary = getSheetPictrues03((NPOI.HSSF.UserModel.HSSFSheet)sheet);
                //获取所有老人基本信息
                IList <OldManBaseInfo> oldManBaseInfoList = RetExistsIdNo(AreaId);
                //获取所有老人配置终端信息
                IList <OldManConfigInfo> oldManConfigInfoList = RetAllConfigCallNo();
                //获取所有老人的亲属资料
                IList <StringObjectDictionary> familyMemberList = RetAllFamilyMember();
                //获取所有街道社区信息
                IList <Area> AreaList = RetAllStreetCommunity();
                //保存图片地址
                //基本信息
                IList <StringObjectDictionary> basedatas = RetEffectiveDatas(datas, ref retFailInfo);
                OldManBaseInfo baseInfo = new OldManBaseInfo()
                {
                    DataSource = GlobalManager.DIKey_00012_UploadFile, OperatedBy = NormalSession.UserId.ToGuid(), OperatedOn = DateTime.Now, AreaId = AreaId
                };
                OldManConfigInfo oldmanconfig = new OldManConfigInfo();
                FamilyMember     familymember = new FamilyMember()
                {
                    Gender = "M", IDNo = "", Status = 1
                };
                OldManFamilyInfo oldmanfamily = new OldManFamilyInfo();

                foreach (var data in basedatas)
                {
                    //老人基本资料
                    baseInfo.OldManId = Guid.NewGuid();
                    count             = oldManBaseInfoList.Count(s => s.IDNo == data["IDNo"].ToString());
                    if (count > 0)
                    {
                        baseInfo.OldManId = oldManBaseInfoList.First(s => s.IDNo == data["IDNo"].ToString()).OldManId;
                    }
                    baseInfo.Status = 1;
                    baseInfo.HealthInsuranceFlag = Convert.ToByte(data["HealthInsuranceNumber"] != null);
                    baseInfo.SocialInsuranceFlag = Convert.ToByte(data["SocialInsuranceNumber"] != null);
                    StringObjectDictionary       sod      = baseInfo.ToStringObjectDictionary(false);
                    IDictionary <string, object> dataItem = sod.MixInObject(data, false, e0571.web.core.Other.CaseSensitive.NORMAL);

                    var tmpArea = AreaList.FirstOrDefault(s => s.AreaName.IndexOf(dataItem["AreaId2"].ToString()) > -1);
                    if (dataItem.ContainsKey("AreaId2") && dataItem["AreaId2"] != null && tmpArea != null)
                    {
                        dataItem["AreaId2"] = tmpArea.AreaId != null?tmpArea.AreaId.ToString().ToUpper() : "";
                    }
                    else
                    {
                        dataItem.Remove("AreaId2");
                    }
                    tmpArea = AreaList.FirstOrDefault(s => s.AreaName.IndexOf(dataItem["AreaId3"].ToString()) > -1);
                    if (dataItem.ContainsKey("AreaId3") && dataItem["AreaId3"] != null && tmpArea != null)
                    {
                        dataItem["AreaId3"] = tmpArea.AreaId != null?tmpArea.AreaId.ToString().ToUpper() : "";
                    }
                    else
                    {
                        dataItem.Remove("AreaId3");
                    }

                    if (count > 0)
                    {
                        statements.Add(new IBatisNetBatchStatement {
                            StatementName = baseInfo.GetUpdateMethodName(), ParameterObject = dataItem, Type = SqlExecuteType.UPDATE
                        });
                    }
                    else
                    {
                        statements.Add(new IBatisNetBatchStatement {
                            StatementName = baseInfo.GetCreateMethodName(), ParameterObject = dataItem, Type = SqlExecuteType.INSERT
                        });
                    }
                    //老人呼叫设备资料,存在则跳过
                    if (dataItem.ContainsKey("CallNo") && dataItem["CallNo"] != null)
                    {
                        if (oldManConfigInfoList.Count(s => s.CallNo == dataItem["CallNo"].ToString()) == 0)
                        {
                            var configinfoitem = oldManConfigInfoList.FirstOrDefault(s => s.OldManId.ToString() == dataItem["OldManId"].ToString());
                            if (configinfoitem != null && configinfoitem.OldManId != null)
                            {
                                oldmanconfig_statements.Add(new IBatisNetBatchStatement {
                                    StatementName = oldmanconfig.GetUpdateMethodName(), ParameterObject = dataItem, Type = SqlExecuteType.UPDATE
                                });
                            }
                            else
                            {
                                oldmanconfig_statements.Add(new IBatisNetBatchStatement {
                                    StatementName = oldmanconfig.GetCreateMethodName(), ParameterObject = dataItem, Type = SqlExecuteType.INSERT
                                });
                            }
                        }
                    }

                    //获取亲人信息
                    StringObjectDictionary sod2 = new StringObjectDictionary();
                    for (int i = 0; i < 3; i++)
                    {
                        string familyName = "FamilyName" + (i + 1).ToString();
                        string callNo     = "CallNo" + (i + 1).ToString();
                        if (!data.ContainsKey(familyName) || data[familyName] == null)
                        {
                            continue;
                        }
                        if (!data.ContainsKey(callNo) || data[callNo] == null)
                        {
                            continue;
                        }

                        oldmanfamily.RelationIdOfFamily = (relationOfMan - i).ToString();
                        oldmanfamily.RelationIdOfOldMan = (relationOfMan - i).ToString();

                        string callNoData = data[callNo].ToString();
                        familymember.FamilyMemberId   = Guid.NewGuid();
                        familymember.FamilyMemberName = data[familyName].ToString();
                        //匹配手机号
                        familymember.Mobile = System.Text.RegularExpressions.Regex.Match(callNoData, @"0*[1][358]\d{9}").Value;
                        if (familymember.Mobile.Length > 0)
                        {
                            callNoData = callNoData.Replace(familymember.Mobile, "");
                        }
                        //匹配座机
                        familymember.Tel = System.Text.RegularExpressions.Regex.Match(callNoData, @"((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))").Value;

                        if (count > 0)
                        {
                            sod2 = familyMemberList.FirstOrDefault(s => s["OldManId"].ToString() == baseInfo.OldManId.ToString() && s["RelationIdOfFamily"].ToString() == oldmanfamily.RelationIdOfFamily);
                            if (sod2 != null && sod2.Count > 0)
                            {
                                if (familyMemberList.Count(s => s["FamilyMemberName"].ToString() == familymember.FamilyMemberName && s["Mobile"].ToString() == familymember.Mobile && s["Tel"].ToString() == familymember.Tel) > 0)
                                {
                                    continue;
                                }
                                familymember.FamilyMemberId = sod2["FamilyMemberId"].ToString().ToGuid();
                            }
                        }
                        sod      = baseInfo.ToStringObjectDictionary(false);
                        dataItem = sod.MixInObject(familymember, false, e0571.web.core.Other.CaseSensitive.NORMAL);
                        if (sod2 != null && sod2.Count > 0)
                        {
                            familymember_statements.Add(new IBatisNetBatchStatement {
                                StatementName = familymember.GetUpdateMethodName(), ParameterObject = dataItem, Type = SqlExecuteType.UPDATE
                            });
                        }
                        else
                        {
                            familymember_statements.Add(new IBatisNetBatchStatement {
                                StatementName = familymember.GetCreateMethodName(), ParameterObject = dataItem, Type = SqlExecuteType.INSERT
                            });
                            dataItem = sod.MixInObject(oldmanfamily, false, e0571.web.core.Other.CaseSensitive.NORMAL);
                            oldmanfamily_statements.Add(new IBatisNetBatchStatement {
                                StatementName = oldmanfamily.GetCreateMethodName(), ParameterObject = dataItem, Type = SqlExecuteType.INSERT
                            });
                        }
                    }
                }

                BuilderFactory.DefaultBulder().ExecuteNativeSqlNoneQuery(statements);
                BuilderFactory.DefaultBulder().ExecuteNativeSqlNoneQuery(oldmanconfig_statements);
                BuilderFactory.DefaultBulder().ExecuteNativeSqlNoneQuery(familymember_statements);
                BuilderFactory.DefaultBulder().ExecuteNativeSqlNoneQuery(oldmanfamily_statements);


                /*string saveName = @context.Request["saveName"];
                 * string fileType = file.FileName.Substring(file.FileName.LastIndexOf("."));
                 * string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"]);
                 * FileAdapter.EnsurePath(uploadPath);
                 * if (string.IsNullOrEmpty(saveName))
                 * {
                 *  file.SaveAs(uploadPath + file.FileName);
                 * }
                 * else
                 * {
                 *  file.SaveAs(uploadPath + saveName + fileType);
                 * }
                 */
                //下面这句代码缺少的话,上传成功后上传队列的显示不会自动消失
                context.Response.Write("1");
            }
            else
            {
                context.Response.Write("0");
            }
        }
        public async Task <IActionResult> AddFamilyMember([FromBody] string familyId,
                                                          int generation,
                                                          int sequence,
                                                          string firstName_Ar,
                                                          int gender,
                                                          string parentFamilyId)
        {
            if (ModelState.IsValid)
            {
                if (string.IsNullOrWhiteSpace(familyId))
                {
                    return(BadRequest($"{nameof(familyId)} cannot be empty"));
                }

                if (string.IsNullOrWhiteSpace(firstName_Ar))
                {
                    return(BadRequest($"{nameof(firstName_Ar)} cannot be empty"));
                }

                if (generation < 0)
                {
                    return(BadRequest($"{nameof(generation)} cannot be less than zero"));
                }

                if (sequence < 1)
                {
                    return(BadRequest($"{nameof(sequence)} cannot be less than 1"));
                }

                if (gender != 1 && gender != 2)
                {
                    return(BadRequest($"{nameof(gender)} can be either 1 (female) or 2 (male)"));
                }

                if (string.IsNullOrWhiteSpace(parentFamilyId))
                {
                    return(BadRequest($"{nameof(parentFamilyId)} cannot be empty"));
                }

                var parentId = 0;

                if (!int.TryParse(parentFamilyId, out parentId))
                {
                    return(BadRequest($"{nameof(parentFamilyId)} is not a valid FamilyId Format"));
                }

                if (parentId < 0)
                {
                    return(BadRequest($"{nameof(parentId)} cannot be less than zero"));
                }

                var familyMember = new FamilyMember
                {
                    FamilyId     = familyId,
                    Generation   = generation,
                    Sequence     = sequence,
                    FirstName_Ar = firstName_Ar,
                    Gender       = (Gender)gender
                };

                var parent = await this._unitOfWork.FamilyMembers.GetFamilyMemberByFamilyIdAsync(parentFamilyId);

                if (parent is null)
                {
                    AddError($"parent family Id {parentFamilyId} is not found!");
                    return(BadRequest(ModelState));
                }

                familyMember.ParentId = parent.Id;

                await this._unitOfWork.FamilyMembers.AddFamilyMemberAsync(familyMember);


                return(CreatedAtAction(AddFamilyMemberActionName, new { id = familyMember.Id }, familyMember));
            }

            return(BadRequest(ModelState));
        }
Exemple #29
0
 public void AddFamilyMember(FamilyMember familyMember)
 {
     this.SqlDbContext.FamilyMembers.Add(familyMember);
 }
 protected void onAddItem()
 {
     showCreator  = true;
     memberToEdit = new FamilyMember();
     StateHasChanged();
 }
        protected int GetPersonIdFromInputData()
        {
            string sFirstName = tbFirstName.Text;
            string sLastName = tbLastName.Text;
            string sEmail = tbEmail.Text;
            string sAddress = tbAddress1.Text;
            string sCity = tbCity.Text;
            string sState = tbState.Text;
            string sZip = tbZip.Text;
            string sPhone = tbPhone.Text;

            PersonCollection personCollection = new PersonCollection();
            personCollection.LoadByEmail(sEmail);

            int iFoundPersonId = -1;
            foreach (Person person in personCollection)
            {
                PersonPhone phoneSearch = new PersonPhone(person.PersonID, FormatPhone(sPhone));

                if ((phoneSearch.PersonID == person.PersonID) && (person.LastName.ToLower() == sLastName.ToLower()))
                {
                    this.currentAddress = person.Addresses.FindByType(41);
                    if(this.currentAddress.Address.PostalCode.Substring(0,5) == sZip )
                    {
                        iFoundPersonId = person.PersonID;
                    }
                }
            }

            if (iFoundPersonId > 0)
            {
                //person in the db
                //easy ride...
            }
            else
            {
                //create the family for the person
                Family family = new Family();
                family.OrganizationID = CurrentArenaContext.Organization.OrganizationID;
                family.FamilyName = sLastName + " Family";

                //add person to the family
                FamilyMember familyMember = new FamilyMember();
                family.FamilyMembers.Add(familyMember);

                //
                // Ensure some of the basics are set correctly.
                //
                if ((familyMember.Campus == null || familyMember.Campus.CampusId == -1) && NewPersonCampusSetting != -1)
                    familyMember.Campus = new Campus(NewPersonCampusSetting);
                if (familyMember.MemberStatus == null || familyMember.MemberStatus.LookupID == -1)
                    familyMember.MemberStatus = new Lookup(NewPersonStatusSetting);
                if (familyMember.RecordStatus == Arena.Enums.RecordStatus.Undefined)
                    familyMember.RecordStatus = Arena.Enums.RecordStatus.Pending;

                //add person to the db
                familyMember.FirstName = sFirstName;
                familyMember.FirstName = sFirstName;
                familyMember.LastName = sLastName;
                familyMember.FamilyRole = new Lookup(new Guid("e410e1a6-8715-4bfb-bf03-1cd18051f815"));
                familyMember.Gender = Arena.Enums.Gender.Unknown;
                familyMember.MaritalStatus = new Lookup(new Guid("9C000CF2-677B-4725-981E-BD555FDAFB30"));

                //add email to db and person to email
                PersonEmail personEmail = new PersonEmail();
                personEmail.Email = sEmail;
                personEmail.Active = true;
                familyMember.Emails.Add(personEmail);

                //add address to db and person to address
                PersonAddress personAddress = new PersonAddress();
                personAddress.Address.StreetLine1 = sAddress;
                personAddress.Address.City = sCity;
                personAddress.Address.State = sState;
                personAddress.Address.PostalCode = sZip;
                personAddress.AddressType = new Lookup(41);
                personAddress.Address.Standardize();
                this.currentAddress = personAddress;
                familyMember.Addresses.Add(personAddress);

                //add phone to db and person to phone
                PersonPhone personPhone = new PersonPhone();
                personPhone.PhoneType = new Lookup(new Guid("f2a0fba2-d5ab-421f-a5ab-0c67db6fd72e"));
                familyMember.Phones.Add(personPhone);
                personPhone.Number = FormatPhone(sPhone);

                //Save All
                family.Save(ModuleUserName);
                familyMember.Save(CurrentOrganization.OrganizationID, ModuleUserName, true);
                familyMember.SaveEmails(CurrentPortal.OrganizationID, ModuleUserName);
                familyMember.SaveAddresses(CurrentPortal.OrganizationID, ModuleUserName);
                familyMember.SavePhones(CurrentPortal.OrganizationID, ModuleUserName);
                familyMember.Save(CurrentUser.Identity.Name);

                iFoundPersonId = familyMember.PersonID;
            }

            return iFoundPersonId;
        }
Exemple #32
0
        private void UpdateFamily()
        {
            int    organizationID = CurrentPortal.OrganizationID;
            string userID         = CurrentUser.Identity.Name;

            if (userID == string.Empty)
            {
                userID = "UserConfirmation.ascx";
            }

            bool newPerson     = (person.PersonID == -1);
            bool newSpouse     = (spouse.PersonID == -1);
            bool spouseUpdated = tbSpouseFirstName.Text.Trim() != string.Empty;

            if (NotificationEmailSetting != string.Empty &&
                (newPerson || (newSpouse && spouseUpdated)))
            {
                SendNotification();
            }
            else
            {
                Lookup memberStatus;
                try
                {
                    memberStatus = new Lookup(Int32.Parse(MemberStatusIDSetting));
                    if (memberStatus.LookupID == -1)
                    {
                        throw new ModuleException(CurrentPortalPage, CurrentModule, "Member Status setting must be a valid Member Status Lookup value.");
                    }
                }
                catch (System.Exception ex)
                {
                    throw new ModuleException(CurrentPortalPage, CurrentModule, "Member Status setting must be a valid Member Status Lookup value.", ex);
                }

                if (newPerson)
                {
                    person.RecordStatus = RecordStatus.Pending;
                    person.MemberStatus = memberStatus;

                    if (CampusSetting != string.Empty)
                    {
                        try { person.Campus = new Arena.Organization.Campus(Int32.Parse(CampusSetting)); }
                        catch { person.Campus = null; }
                    }

                    person.MaritalStatus = new Lookup(SystemLookup.MaritalStatus_Unknown);
                    person.Gender        = Gender.Unknown;
                }

                person.FirstName = tbFirstName.Text.Trim();
                person.LastName  = tbLastName.Text.Trim();

                Lookup      HomePhoneType = new Lookup(SystemLookup.PhoneType_Home);
                PersonPhone HomePhone     = person.Phones.FindByType(HomePhoneType.LookupID);
                if (HomePhone == null)
                {
                    HomePhone           = new PersonPhone();
                    HomePhone.PhoneType = HomePhoneType;
                    person.Phones.Add(HomePhone);
                }
                HomePhone.Number = tbHomePhone.Text.Trim();

                Lookup      CellPhoneType = new Lookup(SystemLookup.PhoneType_Cell);
                PersonPhone CellPhone     = person.Phones.FindByType(CellPhoneType.LookupID);
                if (CellPhone == null)
                {
                    CellPhone           = new PersonPhone();
                    CellPhone.PhoneType = CellPhoneType;
                    person.Phones.Add(CellPhone);
                }
                CellPhone.Number     = tbCellPhone.Text.Trim();
                CellPhone.SMSEnabled = cbCellSMS.Checked;

                person.Emails.FirstActive = tbEmail.Text.Trim();

                Lookup        HomeAddressType = new Lookup(SystemLookup.AddressType_Home);
                PersonAddress HomeAddress     = person.Addresses.FindByType(HomeAddressType.LookupID);
                if (HomeAddress == null)
                {
                    HomeAddress             = new PersonAddress();
                    HomeAddress.AddressType = HomeAddressType;
                    person.Addresses.Add(HomeAddress);
                }
                HomeAddress.Address = new Address(
                    tbStreetAddress.Text.Trim(),
                    string.Empty,
                    tbCity.Text.Trim(),
                    ddlState.SelectedValue,
                    tbZipCode.Text.Trim(),
                    false);
                HomeAddress.Primary = true;

                person.Save(organizationID, userID, false);
                person.SaveAddresses(organizationID, userID);
                person.SavePhones(organizationID, userID);
                person.SaveEmails(organizationID, userID);

                if (spouseUpdated)
                {
                    if (newSpouse)
                    {
                        spouse.RecordStatus = RecordStatus.Pending;
                        spouse.MemberStatus = memberStatus;

                        if (CampusSetting != string.Empty)
                        {
                            try { spouse.Campus = new Arena.Organization.Campus(Int32.Parse(CampusSetting)); }
                            catch { spouse.Campus = null; }
                        }

                        spouse.MaritalStatus = new Lookup(SystemLookup.MaritalStatus_Married);
                        person.MaritalStatus = spouse.MaritalStatus;
                        spouse.Gender        = Gender.Unknown;
                    }

                    spouse.FirstName = tbSpouseFirstName.Text.Trim();
                    spouse.LastName  = tbSpouseLastName.Text.Trim();

                    PersonPhone SpouseHomePhone = spouse.Phones.FindByType(HomePhoneType.LookupID);
                    if (SpouseHomePhone == null)
                    {
                        SpouseHomePhone           = new PersonPhone();
                        SpouseHomePhone.PhoneType = HomePhoneType;
                        spouse.Phones.Add(SpouseHomePhone);
                    }
                    SpouseHomePhone.Number = tbSpouseHomePhone.Text.Trim();

                    PersonPhone SpouseCellPhone = spouse.Phones.FindByType(CellPhoneType.LookupID);
                    if (SpouseCellPhone == null)
                    {
                        SpouseCellPhone           = new PersonPhone();
                        SpouseCellPhone.PhoneType = CellPhoneType;
                        spouse.Phones.Add(SpouseCellPhone);
                    }
                    SpouseCellPhone.Number     = tbSpouseCellPhone.Text.Trim();
                    SpouseCellPhone.SMSEnabled = cbSpouseSMS.Checked;

                    spouse.Emails.FirstActive = tbSpouseEmail.Text.Trim();

                    spouse.Save(organizationID, userID, false);
                    spouse.SaveAddresses(organizationID, userID);
                    spouse.SavePhones(organizationID, userID);
                    spouse.SaveEmails(organizationID, userID);
                }

                if (newPerson)
                {
                    Family family = new Family();
                    family.OrganizationID = organizationID;
                    family.FamilyName     = tbLastName.Text.Trim() + " Family";
                    family.Save(userID);

                    FamilyMember fm = new FamilyMember(family.FamilyID, person.PersonID);
                    fm.FamilyID   = family.FamilyID;
                    fm.FamilyRole = new Lookup(SystemLookup.FamilyRole_Adult);
                    fm.Save(userID);

                    if (spouseUpdated)
                    {
                        fm            = new FamilyMember(family.FamilyID, spouse.PersonID);
                        fm.FamilyID   = family.FamilyID;
                        fm.FamilyRole = new Lookup(SystemLookup.FamilyRole_Adult);
                        fm.Save(userID);
                    }
                }
            }

            if (iRedirect.Value.Trim() != string.Empty)
            {
                StringBuilder sbRedirect = new StringBuilder();
                sbRedirect.Append(iRedirect.Value.Trim());
                sbRedirect.Append("&confirmed=true");

                // If this is a new person, the person object needs to be reloaded to get new GUID
                if (newPerson)
                {
                    person = new Person(person.PersonID);
                }

                sbRedirect.AppendFormat("&person={0}", person.PersonGUID.ToString());

                if (spouseUpdated)
                {
                    if (newSpouse)
                    {
                        spouse = new Person(spouse.PersonID);
                    }

                    sbRedirect.AppendFormat("&spouse={0}", spouse.PersonGUID.ToString());
                }

                Response.Redirect(sbRedirect.ToString(), true);
            }
        }
        /// <summary>
        /// Loads an PersonReference object with the corresponding values in the Person object
        /// </summary>
        /// <param name="person"></param>
        /// <returns>PersonReference - Object</returns>
        public Contracts.PersonReference ConvertPersonToPersonReference(Person person)
        {
            Contracts.PersonReference personReference = new Contracts.PersonReference();

            try
            {
                personReference.Age = person.Age;
            }
            catch { personReference.Age = 0; }
            try
            {
                personReference.AnniversaryDate = person.AnniversaryDate == null || person.AnniversaryDate == Convert.ToDateTime("1900-01-01 00:00:00.000") ? String.Empty : person.AnniversaryDate.ToShortDateString();
            }
            catch { personReference.AnniversaryDate = String.Empty; }
            try
            {
                personReference.BirthDate = person.BirthDate == null || person.BirthDate == Convert.ToDateTime("1900-01-01 00:00:00.000") ? String.Empty : person.BirthDate.ToShortDateString();
            }
            catch { personReference.BirthDate = String.Empty; }
            try
            {
                personReference.Campus = person.Campus.Name;
            }
            catch { personReference.Campus = String.Empty; }
            try
            {
                personReference.City = person.PrimaryAddress.City;
            }
            catch { personReference.City = String.Empty; }

            personReference.FamilyId = person.FamilyId;
            try
            {
                personReference.FamilyIsChild = "false";
                FamilyMember fm = new FamilyMember(person.FamilyId, person.PersonID);
                if (fm.FamilyRole.Value.ToLower() == "child")
                {
                    personReference.FamilyIsChild = "true";
                }
            }
            catch { personReference.FamilyIsChild = "false"; }

            personReference.FirstName = person.FirstName;
            personReference.LastName = person.LastName;
            personReference.MaritalStatus = person.MaritalStatus.Value;
            personReference.NickName = person.NickName;
            personReference.PersonId = person.PersonID;
            personReference.PostalCode = person.PostalCode;
            try
            {
                int peCounter = 0;
                personReference.Emails = new Contracts.GenericListResult<Contracts.EmailReference>();
                personReference.Emails.Items = new List<Contracts.EmailReference>();

                foreach(PersonEmail pe in person.Emails)
                {
                    peCounter++;
                    personReference.Emails.Items.Add(new Contracts.EmailReference(pe.EmailId, pe.Email, pe.Active.ToString(), pe.Order.ToString()));
                }
                personReference.Emails.Max = personReference.Emails.Items.Count;
                personReference.Emails.Total = personReference.Emails.Items.Count;
            }
            catch { }
            try
            {
                int ppCounter = 0;
                personReference.PhoneNumbers = new Contracts.GenericListResult<Contracts.PhoneReference>();
                personReference.PhoneNumbers.Items = new List<Contracts.PhoneReference>();

                foreach (PersonPhone pp in person.Phones)
                {
                    ppCounter++;
                    personReference.PhoneNumbers.Items.Add(new Contracts.PhoneReference(pp.Number, pp.Extension, pp.PhoneType.Value));
                }
                personReference.PhoneNumbers.Max = personReference.PhoneNumbers.Items.Count;
                personReference.PhoneNumbers.Total = personReference.PhoneNumbers.Items.Count;
            }
            catch { }

            personReference.RecordStatusActive = person.RecordStatus == Enums.RecordStatus.Active ? true : false;

            try
            {
                personReference.SpouseFirstName = person.Spouse().FirstName;
            }
            catch { personReference.SpouseFirstName = String.Empty; }
            try
            {
                personReference.SpouseNickName = person.Spouse().NickName;
            }
            catch { personReference.SpouseNickName = String.Empty; }

            return personReference;
        }
Exemple #34
0
        public string GetFamilyMember()
        {
            var attr = FamilyMember.GetAttribute <EnumDescriptionAttribute>();

            return(attr.GetDescription());
        }
        public FamilyMemberResponseDto UpdateAddFamilyMember(FamilyMember FamilyMember, string token)
        {
            int Id      = JwtAuthenticationExtensions.ExtractTokenInformation(token).UserId;
            var Student = context.Students.FirstOrDefault(x => x.UserInfoId == Id && !x.DelFlag);

            if (FamilyMember.Id == 0)
            {
                var familyMember = context.FamilyMembers.Add(new Database.Schema.Entity.FamilyMember
                {
                    StudentId    = Student.Id,
                    Name         = FamilyMember.Name,
                    RelationId   = FamilyMember.RelationId,
                    YearOfBirth  = FamilyMember.YearOfBirth,
                    CareerTypeId = FamilyMember.CareerTypeId,
                });
                context.PersonalInfoes.Add(new Database.Schema.Entity.PersonalInfo
                {
                    Id                 = familyMember.PersonalInfoId,
                    EthnicId           = FamilyMember.EthnicId,
                    ReligionId         = FamilyMember.ReligionId,
                    NationalityId      = FamilyMember.NationalityId,
                    PermanentResidence = FamilyMember.Address
                });
                context.ContactInfoes.Add(new Database.Schema.Entity.ContactInfo
                {
                    Id          = familyMember.ContactId,
                    PhoneNumber = FamilyMember.PhoneNumber,
                    Email       = "*****@*****.**",
                    Address     = FamilyMember.Address,
                });
            }
            else
            {
                var family = context.FamilyMembers.FirstOrDefault(x => x.Id == FamilyMember.Id && !x.DelFlag);
                context.FamilyMembers.Where(x => x.StudentId == Student.Id && x.Id == FamilyMember.Id && !x.DelFlag).Update(x => new Database.Schema.Entity.FamilyMember
                {
                    Name         = FamilyMember.Name,
                    RelationId   = FamilyMember.RelationId,
                    YearOfBirth  = FamilyMember.YearOfBirth,
                    CareerTypeId = FamilyMember.CareerTypeId
                });

                context.PersonalInfoes.Where(x => x.Id == family.PersonalInfoId && !x.DelFlag).Update(x => new Database.Schema.Entity.PersonalInfo
                {
                    EthnicId           = FamilyMember.EthnicId,
                    ReligionId         = FamilyMember.ReligionId,
                    NationalityId      = FamilyMember.NationalityId,
                    PermanentResidence = FamilyMember.Address
                });
                context.ContactInfoes.Where(x => x.Id == family.ContactId && !x.DelFlag).Update(x => new Database.Schema.Entity.ContactInfo
                {
                    PhoneNumber = FamilyMember.PhoneNumber,
                    Email       = FamilyMember.Email,
                    Address     = FamilyMember.Address
                });
            }
            context.SaveChanges();
            return(new FamilyMemberResponseDto()
            {
                Id = FamilyMember.Id
            });
        }
 static void Main(string[] args)
 {
     FamilyMember member = Create <FamilyMember, FamilyRelation>(FamilyRelation.Sister);
 }