Exemplo n.º 1
0
 public void TakeBet(Bettor bettor, BetOption outcome, Brother brother)
 {
     if (bettor == null)
     {
         throw new ArgumentNullException(nameof(bettor));
     }
     if (bettor.Id == default(int))
     {
         throw new ArgumentException(nameof(bettor));
     }
     if (outcome == null)
     {
         throw new ArgumentNullException(nameof(outcome));
     }
     if (outcome.Id == default(int))
     {
         throw new ArgumentException(nameof(outcome));
     }
     if (brother == null)
     {
         throw new ArgumentNullException(nameof(brother));
     }
     if (brother.Id == default(int))
     {
         throw new ArgumentException(nameof(brother));
     }
     _betRepository.TakeBet(bettor, outcome, brother);
 }
Exemplo n.º 2
0
 public static string GetBrother(string lang, string str, Brother brother)
 {
     Language language = availableLang.FirstOrDefault(item => item.LanguageName == lang.ToLowerInvariant());
     if (language == null)
         return null;
     return language.GetBrother(str, brother);
 }
Exemplo n.º 3
0
 public void Add(Bet bet, Bettor bettor, Brother brother)
 {
     bet.Brother = _context.Brothers.Find(brother.Id);
     bet.Creator = _context.Bettors.Find(bettor.Id);
     _context.Bets.Add(bet);
     _context.SaveChanges();
 }
Exemplo n.º 4
0
        public async Task <IActionResult> PutBrother(int id, Brother brother)
        {
            brother.Id = id;
            if (id != brother.Id)
            {
                return(BadRequest());
            }

            var brotherMod = _context.Brothers.Find(id);

            brotherMod.Name      = brother.Name;
            brotherMod.Surname   = brother.Surname;
            brotherMod.Email     = brother.Email;
            brotherMod.Telephone = brother.Telephone;

            _context.Brothers.Update(brotherMod);

            try
            {
                await _context.SaveChangesAsync();
            } catch (DbUpdateConcurrencyException)
            {
                if (!BrotherExist(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
            return(NoContent());
        }
Exemplo n.º 5
0
        public async Task UpdateBrother_ChangesArePersisted()
        {
            ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(new[] {
                new Claim(JwtClaimTypes.Scope, Constants.Scopes.Administrator),
                new Claim(JwtClaimTypes.Subject, "some-subject"),
                new Claim(JwtClaimTypes.Scope, "directory")
            }));

            int id = _dbContext.Brother.Add(new Brother()).Entity.Id;
            await _dbContext.SaveChangesAsync();

            BrotherController controller = new BrotherController(_dbContext, principal, Mock.Of <ILogger <BrotherController> >());

            Brother brother = new Brother {
                Id        = id,
                FirstName = "firstname1",
                LastName  = "lastname1"
            };

            OkResult result = await controller.UpdateBrother(id, brother) as OkResult;

            Assert.Multiple((() => {
                Assert.That(result, Is.Not.Null);
                Brother changed = _dbContext.Brother.FirstOrDefault(b => b.Id == id);
                Assert.That(changed, Is.Not.Null);
                Assert.That(changed.FirstName, Is.EqualTo("firstname1"));
                Assert.That(changed.LastName, Is.EqualTo("lastname1"));
            }));
        }
 public EditBrotherWithoutBigDialog(Brother brother)
 {
     EditBrotherWithoutBig_Initialize();
     brotherUnderEdit = brother;
     lblEditBig.Text = string.Format(Util.GetLocalizedString("PromptUserForFullName"), brother);
     tbEditBig.AutoCompleteCustomSource = FamilyTreeForm.CurrentBrothers;
     btnCancelEdit.Enabled = true;
 }
        public async Task FindBrotherById_ReturnsCorrectBrother()
        {
            Brother b = await _dbContext.Brother.FindBrotherByIdAsync(2);

            Assert.Multiple(() => {
                Assert.That(b, Is.Not.Null);
                Assert.That(b.Id, Is.EqualTo(2));
            });
        }
Exemplo n.º 8
0
        public static string GetBrother(string lang, string str, Brother brother)
        {
            Language language = availableLang.FirstOrDefault(item => item.LanguageName == lang.ToLowerInvariant());

            if (language == null)
            {
                return(null);
            }
            return(language.GetBrother(str, brother));
        }
 private void EditBrotherWithoutBig_Ok_onClick(object sender, EventArgs eventArgs)
 {
     var b = FamilyTreeForm.Root.FindDescendant( tbEditBig.Text );
     if( b == null )
     {
         var space = tbEditBig.Text.IndexOf(' ');
         b = new Brother(tbEditBig.Text.Substring(space + 1), tbEditBig.Text.Substring(0, space), Util.DefaultInitiationTerm, Util.DefaultYear);
         FamilyTreeForm.Root.AddChild( b );
     }
     b.AddChild( brotherUnderEdit );
 }
Exemplo n.º 10
0
        public async Task <IActionResult> UpdateBrother(int brotherId, [FromBody] Brother newBrotherModel)
        {
            Brother brother = await _dbContext.Brother.FindBrotherByIdAsync(brotherId);

            if (brother == null)
            {
                return(NotFound());
            }

            if (newBrotherModel.Id != brotherId)
            {
                return(BadRequest());
            }

            string?subject = _principal.GetSubjectId();

            if (string.IsNullOrEmpty(subject))
            {
                // Well, this shouldn't happen, but just to be sure.
                return(Unauthorized());
            }

            IEnumerable <string> scopes = _principal.GetScopes();

            // TODO: I think there's a better way to do this (and the bit above), having the authorization filter do it instead, though this requires several things:
            // (1) the route to be consistent; (2) the parameter to either be obtained from the route in the authorization handler or obtainable
            // there via an injected service; and (3) access to the claims principal.
            // However, doing this would prevent this boilerplate every time. It should also be its own authorization policy so that it doesn't apply everywhere.
            if (!subject.Equals(brother.Id.ToString()))
            {
                // If the user isn't the brother they're trying to update and doesn't have the administrator scope, reject the request.
                if (!scopes.Contains(Constants.Scopes.Administrator))
                {
                    _logger.LogInformation("Rejecting request from user with identifier {subject} attempting to modify {brotherFirst} {brotherLast}: the user is not an administrator.",
                                           subject, brother.FirstName, brother.LastName);
                    return(Unauthorized());
                }

                // User is an administrator
                _logger.LogTrace("Administrator (subject {subjectId}) updating {first} {last}.", subject,
                                 brother.FirstName, brother.LastName);
            }

            try {
                _dbContext.Entry(brother).CurrentValues.SetValues(newBrotherModel);

                await _dbContext.SaveChangesAsync();
            } catch (DbUpdateConcurrencyException) {
                return(Conflict());
            }

            return(Ok());
        }
Exemplo n.º 11
0
        public void AddBet(Bet bet, Bettor bettor, Brother betTarget, string[] predictedOutcomes)
        {
            if (bet == null)
            {
                throw new ArgumentNullException(nameof(bet));
            }
            if (bet.Id != default(int))
            {
                throw new ArgumentException(nameof(bet));
            }
            if (bettor == null)
            {
                throw new ArgumentNullException(nameof(bettor));
            }
            if (bettor.Id == default(int))
            {
                throw new ArgumentException(nameof(bettor));
            }
            if (betTarget == null)
            {
                throw new ArgumentNullException(nameof(betTarget));
            }
            if (betTarget.Id == default(int))
            {
                throw new ArgumentException(nameof(betTarget));
            }
            if (predictedOutcomes == null)
            {
                throw new ArgumentNullException(nameof(predictedOutcomes));
            }

            if (bet.Expiration < DateTime.Today.AddDays(2))
            {
                throw new Exception(
                          $"Come on, you need to give more time than that! Set the date to at least {DateTime.Today.AddDays(2).ToShortDateString()}");
            }

            var betOutcomes = predictedOutcomes
                              .Where(o => !string.IsNullOrWhiteSpace(o))
                              .Select(o => new BetOption()
            {
                Outcome = o, Bet = bet
            });

            bet.BetOptions = new List <BetOption>(betOutcomes);
            if (bet.BetOptions.Count < 2)
            {
                throw new Exception("Bets must have at least two outcomes");
            }
            _betRepository.Add(bet, bettor, betTarget);
        }
Exemplo n.º 12
0
        public async Task <ActionResult <Brother> > PostBrother(BrotherResponse brotherResponse)
        {
            var friendTake = await _context.Friends.FirstOrDefaultAsync(z => z.Id == brotherResponse.Friend.Id);

            brotherResponse.Friend = friendTake;
            Brother brother = new Brother {
                Name = brotherResponse.Name, Surname = brotherResponse.Surname, Email = brotherResponse.Email, Telephone = brotherResponse.Telephone, Friend = brotherResponse.Friend
            };

            _context.Brothers.Add(brother);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetBrother", new { id = brother.Id }, brother));
        }
Exemplo n.º 13
0
        public string GetBrother(string ycName, Brother brother)
        {
            if (String.IsNullOrEmpty(ycName) || 
                !tokenInfos.ContainsKey(ycName))
                return null;

            switch (brother)
            {
                case Brother.Left:
                    return tokenInfos[ycName].LeftPair;
                case Brother.Right:
                    return tokenInfos[ycName].RightPair;
                default:
                    return null;
            }
        }
Exemplo n.º 14
0
        public async Task <IActionResult> ReplacePicture(int brotherId, [FromForm] IFormFile?picture)
        {
            string? subjectId = _principal.GetSubjectId();
            Brother brother   = await _dbContext.Brother.FindBrotherByIdAsync(brotherId);

            if (brother == null)
            {
                _logger.LogInformation("Received request to modify picture for brother {id} but they do not exist.", brotherId);
                return(NotFound());
            }

            _logger.LogInformation("Received request to modify picture for brother {brotherId} ({first} {last}).", brotherId, brother.FirstName, brother.LastName);

            // TODO: The subject id is not necessarily the same as the brother id. They should be linked by a column in the Brother table that does not yet exist.
            IEnumerable <string> scopes = _principal.GetScopes();

            if (!brotherId.ToString().Equals(subjectId, StringComparison.OrdinalIgnoreCase))
            {
                if (!scopes.Contains(Constants.Scopes.Administrator))
                {
                    _logger.LogTrace("Rejecting request to modify another user's picture from non-administrator user {subject}.", subjectId);
                    return(Unauthorized());
                }

                // User is an administrator
                _logger.LogTrace("Administrator replacing picture for {brother}.", brotherId);
            }

            if (picture == null || picture.Length == 0)
            {
                _logger.LogTrace("Clearing picture.");
                brother.Picture = null;
            }
            else
            {
                brother.Picture = new byte[picture.Length];
                await picture.OpenReadStream().ReadAsync(brother.Picture, 0, (int)picture.Length);
            }

            try {
                await _dbContext.SaveChangesAsync();
            } catch (DBConcurrencyException) {
                return(Conflict());
            }

            return(Ok());
        }
        public ActionResult Edit(int id, Brother brotherN)
        {
            try
            {
                var client = new RestClient();

                var request = new RestRequest("http://localhost:5003/api/Brothers/" + id, DataFormat.Json);
                request.AddJsonBody(brotherN);
                var response = client.Put <Brother>(request);

                return(Redirect("/friend/index"));
            }
            catch
            {
                return(View());
            }
        }
Exemplo n.º 16
0
        public void TakeBet(Bettor bettor, BetOption outcome, Brother brother)
        {
            brother = _context.Brothers.Find(brother.Id);
            var prediction = new Prediction()
            {
                Bettor           = _context.Bettors.Find(bettor.Id),
                OutcomePredicted = _context.BetOptions.Find(outcome.Id),
                TimeOfPrediction = DateTime.Now
            };

            if (brother.Predictions == null)
            {
                brother.Predictions = new List <Prediction>();
            }
            brother.Predictions.Add(prediction);
            _context.SaveChanges();
        }
Exemplo n.º 17
0
        public IActionResult GetPicture(int id)
        {
            Brother brother = _dbContext.Brother.FirstOrDefault(b => b.Id == id);

            if (brother == null)
            {
                return(NotFound());
            }

            if (brother.Picture == null)
            {
                return(GetDefaultPicture());
            }

            // TODO: I think this works for JPEG and PNG images, but need to verify.
            return(File(brother.Picture, "image/jpeg"));
        }
Exemplo n.º 18
0
        public string GetBrother(string ycName, Brother brother)
        {
            if (String.IsNullOrEmpty(ycName) ||
                !tokenInfos.ContainsKey(ycName))
            {
                return(null);
            }

            switch (brother)
            {
            case Brother.Left:
                return(tokenInfos[ycName].LeftPair);

            case Brother.Right:
                return(tokenInfos[ycName].RightPair);

            default:
                return(null);
            }
        }
Exemplo n.º 19
0
        public ActionResult AddNewBrother(Brother bro)
        {
            bI_BLL = new BrothersInfo_BLL();

            if (ModelState.IsValid)
            {
                if (bI_BLL.requestBrotherAddition(bro) == true)
                {
                    return(View("BrotherAdditionSuccess"));
                }
                else
                {
                    //The brother must already exist.
                    return(View("Nope"));
                }
            }
            //Model state is not valid, so return the BrotherAdditionFaield
            else
            {
                return(View("BrotherAdditionFailed"));
            }
        }
Exemplo n.º 20
0
        public async Task UpdateBrother_DbConcurrencyExceptionIsThrownOnSave_ReturnsConflictAndRecordIsUnchanged()
        {
            ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(new[] {
                new Claim(JwtClaimTypes.Scope, Constants.Scopes.Administrator),
                new Claim(JwtClaimTypes.Subject, "some-subject"),
                new Claim(JwtClaimTypes.Scope, "directory")
            }));

            int id = _dbContext.Brother.Add(new Brother {
                FirstName = "ShouldNot", LastName = "BeModified"
            }).Entity.Id;
            await _dbContext.SaveChangesAsync();

            Mock <DirectoryContext> mockedContext = new Mock <DirectoryContext>();

            mockedContext.SetupGet(m => m.Brother).Returns(_dbContext.Brother);
            List <IUpdateEntry> entries = new List <IUpdateEntry>(new[] { Mock.Of <IUpdateEntry>() });

            mockedContext.Setup(m => m.Entry(It.IsAny <Brother>())).Throws(new DbUpdateConcurrencyException(string.Empty, entries));

            BrotherController controller = new BrotherController(mockedContext.Object, principal, Mock.Of <ILogger <BrotherController> >());

            Brother brother = new Brother {
                Id        = id,
                FirstName = "firstname1",
                LastName  = "lastname1"
            };

            ConflictResult result = await controller.UpdateBrother(id, brother) as ConflictResult;

            Assert.Multiple((() => {
                Assert.That(result, Is.Not.Null);
                Brother changed = _dbContext.Brother.FirstOrDefault(b => b.Id == id);
                Assert.That(changed, Is.Not.Null);
                Assert.That(changed.FirstName, Is.EqualTo("ShouldNot"));
                Assert.That(changed.LastName, Is.EqualTo("BeModified"));
            }));
        }
        private void mainFrame_onLoad(object sender, EventArgs eventArguments)
        {
            Brother.SelectCallback = EditBrotherPanel_Initalize;
            Brother.ShiftCallback = BoundsCheckShift;

            var start = new ImportDataForm();
            start.ShowDialog();
            if( start.DialogResult != DialogResult.OK )
            {
                Close();
                return;
            }

            displayApex = displayRootOfAllTreeToolStripMenuItem.Checked;
            isXml = start.IsXml;

            if( isXml )
            {
                AutoSave.Elapsed += AutoSave_Elapsed;
                AutoSave.Interval = 30000;
                openXmlFilePath = start.FilePath;
                xmlParentNodeName = start.ParentNode;
                saveXmlToolStripMenuItem.Enabled = true;
            }
            else
            {
                Root = new Brother( Util.DefaultLastName, Util.DefaultFirstName, Util.DefaultInitiationTerm, Util.DefaultYear );

                isMale = start.IsMale;

                bool ret;

                if( start.Connection != null ) 
                {
                    ret = Database_Connect( start.Connection );
                }
                else
                {
                    var server = start.Server;
                    var db = start.Base;
                    var user = start.Username;
                    var pword = start.Password;
                    var portNum = start.Port;

                    ret = Database_Connect( server, portNum, db, user, pword );
                }

                if( !ret )
                {
                    Close();
                    return;
                }
            }

            genderDependentName = isMale 
                ? Util.GetLocalizedString("MaleName") 
                : Util.GetLocalizedString("FemaleName");

            PopulateBrothers( isXml );
            tbBig.AutoCompleteCustomSource = CurrentBrothers;
            tbSelectedBig.AutoCompleteCustomSource = CurrentBrothers;
            tbSelectedLittles.AutoCompleteCustomSource = CurrentBrothers;
            tbLittles.AutoCompleteCustomSource = CurrentBrothers;
            Text = genderDependentName + Util.GetLocalizedString("Tree") + (xmlParentNodeName != string.Empty ? " - " + xmlParentNodeName : string.Empty);
            Root.Label.ContextMenuStrip = cmNodeActions;

            if( !isXml )
            {
                writeBackReady = true;
            }

            Settings.Default.Save();
        }
 private void RemoveBrotherFromTree(Brother brother)
 {
     var name = brother.ToString();
     lbNoRelation.Items.Remove( brother );
     cbTreeParent.Items.Remove( brother );
     CurrentBrothers.Remove( name );
     RefreshNoBigListBox( Root );
     DisplayTree( true );
 }
Exemplo n.º 23
0
        public PaperStatusResult CheckPaperStatus(string brand, string model, string vid, string pid, bool enableTextFileStatus)
        {
            try
            {
                if (string.IsNullOrEmpty(brand))
                {
                    return(new PaperStatusResult {
                        IsSuccess = false, ErrorMessage = "brand cannot be null or empty."
                    });
                }

                if (string.IsNullOrEmpty(vid))
                {
                    return(new PaperStatusResult {
                        IsSuccess = false, ErrorMessage = "vid cannot be null or empty."
                    });
                }

                if (string.IsNullOrEmpty(pid))
                {
                    return(new PaperStatusResult {
                        IsSuccess = false, ErrorMessage = "pid cannot be null or empty."
                    });
                }

                string[] listPaperStatus;

                if (brand.ToLower().Trim() == "brother")
                {
                    Brother service = new Brother();
                    listPaperStatus = service.CheckPaperStatus(model, vid, pid);
                }
                else if (brand.ToLower().Trim() == "custom")
                {
                    Custom service = new Custom();
                    listPaperStatus = service.CheckPaperStatus(model, vid, pid);
                }
                else
                {
                    return(new PaperStatusResult {
                        IsSuccess = false, ErrorMessage = "brand not match."
                    });
                }

                if (enableTextFileStatus)
                {
                    string MessageStorageFolder = ConfigurationManager.AppSettings["RMS.MessageStorageFolder"];
                    if (!string.IsNullOrEmpty(MessageStorageFolder))
                    {
                        Directory.CreateDirectory(MessageStorageFolder);

                        // ทำการลบไฟล์ status ออกจาก folder
                        // โดยการดึงรายชื่อไฟล์ทั้งหมดของอุปกรณ์นั้น ไปเทียบกับใน result list
                        // หากชื่อไฟล์ ไม่อยู่ใน list ให้ลบทิ้ง (ทั้งนี้ list ต้องมีข้อมูลอยู่ หากไม่มีเลย แสดงว่า ดึง status ไม่ได้ ให้ข้ามการลบไป)

                        // ถ้ามีข้อมูล status ใน list ให้ทำการลบไฟล์ ที่ไม่เกียวข้อง
                        if (listPaperStatus.Length > 0)
                        {
                            string[] listFileStatus = Directory.GetFiles(MessageStorageFolder, "*_" + brand + ".txt");
                            if (listPaperStatus[0] != null && listPaperStatus[0].ToLower() == "ok")
                            {
                                //แสดงว่า status ปกติ ให้ลบไฟล์ทั้งหมด
                                foreach (var filestatus in listFileStatus)
                                {
                                    try
                                    {
                                        File.Delete(filestatus);
                                    }
                                    catch (Exception ex)
                                    {
                                        new RMSAppException(this, "0500", "CheckPaperStatus failed. " + filestatus + " cannot be deleted. " + ex.Message, ex, true);
                                    }
                                }
                            }
                            else
                            {
                                //ให้เลือกลบที่ไม่เกี่ยวข้อง
                                foreach (var filestatus in listFileStatus)
                                {
                                    // คัดกรองรูปแบบ text file
                                    // [STATUS]_[BRAND].txt
                                    string statusFromFile = Path.GetFileNameWithoutExtension(filestatus).Replace("_" + brand, "");
                                    if (listPaperStatus.All(a => a.ToLower() != statusFromFile.ToLower()))
                                    {
                                        try
                                        {
                                            File.Delete(filestatus);
                                        }
                                        catch (Exception ex)
                                        {
                                            new RMSAppException(this, "0500", "CheckPaperStatus failed. " + filestatus + " cannot be deleted. " + ex.Message, ex, true);
                                        }
                                    }
                                }
                            }
                        }

                        // ถ้าไม่ใช่ OK status ให้เริ่มเขียน text file
                        foreach (var paperStatus in listPaperStatus)
                        {
                            if (paperStatus.ToLower() != "ok")
                            {
                                try
                                {
                                    using (File.Create(MessageStorageFolder + paperStatus.ToUpper() + "_" + brand.ToUpper() + ".txt"))
                                    {
                                    }
                                }
                                catch (Exception ex)
                                {
                                    new RMSAppException(this, "0500", "CheckPaperStatus failed. " + MessageStorageFolder + paperStatus.ToUpper() + "_" + brand.ToUpper() + ".txt" + " cannot be created. " + ex.Message, ex, true);
                                }
                            }
                        }
                    }
                }
                return(new PaperStatusResult {
                    IsSuccess = true, ListStatus = listPaperStatus
                });
            }
            catch (Exception ex)
            {
                return(new PaperStatusResult {
                    IsSuccess = false, ErrorMessage = ex.Message
                });
            }
        }
Exemplo n.º 24
0
 void Awake()
 {
     bro = GameObject.FindObjectOfType <Brother>();
 }
        private void AddBrother_onClick(object sender, EventArgs eventArguments)
        {
            var bigName = tbBig.Text;
            var littles = tbLittles.Text.Split( new[] {'\n', '\r'}, StringSplitOptions.RemoveEmptyEntries );
            var last = tbLastName.Text;
            var first = tbFirstName.Text;
            var month = cbIniMonth.Text;
            var year = int.Parse( dtpIniYear.Text );

            if( bigName == string.Empty )
            {
                bigName = Root.ToString();
            }

            var space = bigName.LastIndexOf(' ');
            Brother tmpBig;
            var tmp = Root.FindDescendant( bigName );
            if( tmp != null ) 
            {
                tmpBig = tmp;
            }
            else
            {
                tmpBig = new Brother( bigName.Substring( space + 1 ), bigName.Substring( 0, space ), Util.DefaultInitiationTerm, Util.DefaultYear )
                {
                    Label = {ContextMenuStrip = cmNodeActions}
                };
                Root.AddChild( tmpBig );
            }

            Brother newB;
            tmp = Root.FindDescendant( Util.FormatName(first, last) );
            
            if( tmp == null )
            {
                newB = new Brother( last, first, month, year )
                {
                    Label = {ContextMenuStrip = cmNodeActions}
                };
                tmpBig.AddChild(newB);
            }
            else
            {
                newB = tmp;
                tmpBig.AddChild(newB);
            }

            for ( var i = 0; i < littles.Length; i++ ) 
            {
                space = littles[i].LastIndexOf( ' ' );
                tmp = Root.FindDescendant(littles[i]);

                Brother littleBrother;
                if( tmp == null )
                {
                    littleBrother = new Brother(littles[i].Substring(space + 1), littles[i].Substring(0, space), Util.DefaultInitiationTerm, newB.InitiationYear + 1)
                    {
                        Label = {ContextMenuStrip = cmNodeActions}
                    };
                    littleBrother.Label.ContextMenuStrip = cmNodeActions;
                    newB.AddChild(littleBrother);
                }
                else
                {
                    littleBrother = tmp;
                    newB.AddChild(littleBrother);
                }
            }

            AddBrotherPanel_ClearValues();

            if( cbTreeParent.Enabled == false )
            {
                cbTreeParent.Enabled = true;
                updwnNumGen.Enabled = true;
            }

            RefreshNoBigListBox( Root );
            DisplayTree( true );
            cbTreeParent.Sorted = true;
        }
        private void AddLabelsToPanel(Brother parent, int generations) 
        {
            if( generations < 0 ) return; 

            var count = parent.ChildCount;
            parent.PreliminaryLocation = 0;
            parent.Modifier = 0;
            parent.Label.AutoSize = !fixedWidth;

            if( !parent.Ignored )
            {
                pnlTree.Controls.Add( parent.Label );
            }

            if( parent.Label.AutoSize )
            {
                maximumWidth = Math.Max( maximumWidth, parent.Label.Width );
                parent.Width = parent.Label.Width;
            }
            else
            {
                parent.Label.AutoSize = true;
                parent.Label.Parent.Refresh();
                maximumWidth = Math.Max( maximumWidth, parent.Label.Width );
                parent.Label.AutoSize = false;
            }

            for ( var i = 0; i < count; i++ ) 
            {
                if( !parent[i].Ignored )
                {
                    AddLabelsToPanel( (Brother) parent[i], generations - 1 );
                }
            }
        }
        private void EditBrotherPanel_Initalize(Brother brother)
        {
            selectedEdits = FieldEdit.None;
            splitTreeInfo.Panel2Collapsed = false;
            cbSelectedTerm.Enabled = false;
            dtpSelectedYear.Enabled = false;
            tbSelectedFirst.Enabled = false;
            tbSelectedLast.Enabled = false;
            tbSelectedBig.Enabled = false;
            tbSelectedLittles.Enabled = false;
            btnApplySelected.Enabled = false;
            btnCancelSelected.Enabled = false;
            chbActive.Enabled = false;

            if( selected != null && selected != brother )
            {
                var oldWidth = selected.Label.Width;
                selected.Label.Font = new Font( selected.Label.Font, selected.Label.Font.Style & ~FontStyle.Bold );
                selected.Label.Refresh();
                selected.Label.Location = new Point( selected.Label.Location.X + (oldWidth - selected.Label.Width) / 2,
                    selected.Label.Location.Y );
            }

            selected = brother;

            if( selected != null )
            {
                tbSelectedFirst.Text = brother.FirstName;
                tbSelectedLast.Text = brother.LastName;
                tbSelectedBig.Text = brother.HasParent()
                    ? ((Brother)brother.GetParent()).ToString()
                    : string.Empty;
                tbSelectedLittles.Text = string.Empty;

                for (var i = 0; i < brother.ChildCount; i++)
                {
                    var littleBrother = (Brother)brother[i];
                    tbSelectedLittles.Text += (i == 0 ? string.Empty : Environment.NewLine) + littleBrother;
                }

                dtpSelectedYear.Value = new DateTime(brother.InitiationYear, 1, 1);
                if( brother.InitiationTerm.ToString() != string.Empty )
                {
                    cbSelectedTerm.SelectedItem = brother.InitiationTerm.ToString();
                }

                chbActive.Checked = brother.Active;
            }
            
            btnEditSelected.Enabled = true;
        }
Exemplo n.º 28
0
 private void Brother_pressed(object sender, TappedRoutedEventArgs e)
 {
     Brother.Play();
 }
Exemplo n.º 29
0
        public async Task ActiveBrothers_AreInCorrectOrder()
        {
            await _dbContext.Database.EnsureDeletedAsync();

            _dbContext.SaveChanges();

            DateTime       sameDate    = DateTime.Now;
            List <Brother> brotherList = new List <Brother> {
                // Should be 1 (Zeta number)
                new Brother {
                    FirstName = "FName", LastName = "LName", ExpectedGraduation = DateTime.MaxValue, ZetaNumber = 1
                },
                // Should be 2 (Zeta number)
                new Brother {
                    FirstName = "FName1", LastName = "LName1", ExpectedGraduation = DateTime.MaxValue, ZetaNumber = 2
                },
                // Should be 3 (Join date)
                new Brother {
                    FirstName = "FName2", LastName = "LName2", ExpectedGraduation = DateTime.MaxValue, DateJoined = sameDate.AddDays(-5)
                },
                // Should be 4 (Join date)
                new Brother {
                    FirstName = "FName3", LastName = "LName3", ExpectedGraduation = DateTime.MaxValue, DateJoined = sameDate.AddDays(-3)
                },
                // Should be 5 (Last name)
                new Brother {
                    FirstName = "ZFirst", LastName = "ALast", ExpectedGraduation = DateTime.MaxValue, DateJoined = sameDate
                },
                // Should be 6 (First name)
                new Brother {
                    FirstName = "AFirst", LastName = "ZLast", ExpectedGraduation = DateTime.MaxValue, DateJoined = sameDate
                },
                // Should be 7 (First name)
                new Brother {
                    FirstName = "ZFirst", LastName = "ZLast", ExpectedGraduation = DateTime.MaxValue, DateJoined = sameDate
                }
            };

            DirectoryContext dbContext = new DirectoryContext(new DbContextOptionsBuilder <DirectoryContext>()
                                                              .UseInMemoryDatabase("directory")
                                                              .Options);
            await dbContext.Brother.AddRangeAsync(brotherList);

            await dbContext.SaveChangesAsync();

            BrotherController controller = new BrotherController(dbContext, new ClaimsPrincipal(), Mock.Of <ILogger <BrotherController> >());

            Assert.Multiple(() => {
                OkObjectResult result = controller.GetBrothers() as OkObjectResult;
                Assert.That(result, Is.Not.Null);

                IEnumerable <MinimalBrother> brothers = (result.Value as ContentModel <MinimalBrother>)?.Content;
                Assert.That(brothers, Is.Not.Null);

                Assert.That(brothers.Count(), Is.EqualTo(7));

                for (int i = 0; i < brotherList.Count; i++)
                {
                    MinimalBrother actual = brothers.ElementAt(i);
                    Brother expected      = brotherList[i];

                    Assert.That(actual.LastName, Is.EqualTo(expected.LastName));
                    Assert.That(actual.FirstName, Is.EqualTo(expected.FirstName));
                    Assert.That(actual.ZetaNumber, Is.EqualTo(expected.ZetaNumber));
                    Assert.That(actual.DateJoined, Is.EqualTo(expected.DateJoined));
                }
            });
        }
        private void ImportFromXml( )
        {
            if( !File.Exists( openXmlFilePath ) )
            {
                GenerateSampleXml( openXmlFilePath );
            }

            xmlDocument.Load( openXmlFilePath );

            if( xmlDocument.DocumentElement.ChildNodes.Count != 1 ) throw new Exception("More than one root node, please check your XML and try again.");

            var currentParent = xmlDocument.DocumentElement.FirstChild;
            if( Root == null )
            {
                var last = currentParent.Attributes["Last"].Value;
                var first = currentParent.Attributes["First"].Value;
                var term = currentParent.Attributes["IniTerm"].Value;
                var year = int.Parse( currentParent.Attributes["IniYear"].Value );

                Root = new Brother( last, first, term, year )
                {
                    Active = Util.ConvertStringToBool( currentParent.Attributes["Active"].Value ),
                    Label =
                    {
                        ContextMenuStrip = cmNodeActions
                    }
                };
            }

            foreach (XmlNode child in currentParent.ChildNodes)
            {
                Root.AddChild(ConvertXmlToTree(child));
            }

            saveXmlToolStripMenuItem.Enabled = true;

            if( xmlParentNodeName == null )
            {
                xmlParentNodeName = xmlDocument.DocumentElement.Name;
            }

            Export_ToXml_Perform(openXmlFilePath + Util.GetLocalizedString("DotBak"), xmlParentNodeName); 
            AutoSave.Start();
        }
        private static XmlNode ConvertTreeToXml( XmlDocument xml, Brother brother) 
        {
            XmlNode node = xml.CreateElement("Brother");
            if( node.Attributes == null ) return null;

            var last = xml.CreateAttribute("Last");
            last.Value = brother.LastName;
            node.Attributes.Append(last);

            var first = xml.CreateAttribute("First");
            first.Value = brother.FirstName;
            node.Attributes.Append(first);

            var term = xml.CreateAttribute("IniTerm");
            term.Value = brother.InitiationTerm.ToString();
            node.Attributes.Append(term);

            var year = xml.CreateAttribute("IniYear");
            year.Value = brother.InitiationYear.ToString();
            node.Attributes.Append(year);

            var active = xml.CreateAttribute("Active");
            active.Value = brother.Active.ToString();
            node.Attributes.Append(active);
            
            for ( var i = 0; i < brother.ChildCount; i++ )
            {
                var result = ConvertTreeToXml( xml, (Brother) brother[i] );
                node.AppendChild(result);
            }

            return node;
        }
Exemplo n.º 32
0
    private static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("欢迎来到.net高级班公开课之设计模式特训,今天是Eleven老师为大家带来的观察者模式");

            {
                Cat cat = new Cat();
                cat.Miao();

                Console.WriteLine("*************Observer***************");
                {
                    Brother brother = new Brother();

                    cat.AddObserver(new Mouse());
                    cat.AddObserver(new Dog());
                    cat.AddObserver(new Cricket());
                    cat.AddObserver(new Baby());
                    cat.AddObserver(new Father());
                    cat.AddObserver(new Mother());
                    cat.AddObserver(brother);
                    cat.AddObserver(new Neighbor());
                    cat.AddObserver(new Stealer());

                    cat.MiaoObserver();

                    cat.RemoveObserver(brother);
                    cat.MiaoObserver();
                }
                {
                    Console.WriteLine("*************Event***************");

                    Brother brother = new Brother();

                    cat.CatMiaoEvent += new Mouse().Run;
                    cat.CatMiaoEvent += () => new Dog().Wang("3");
                    cat.CatMiaoEvent += new Cricket().Sing;
                    cat.CatMiaoEvent += new Baby().Cry;
                    cat.CatMiaoEvent += new Father().Roar;
                    cat.CatMiaoEvent += new Mother().Whisper;
                    cat.CatMiaoEvent += brother.Turn;
                    cat.CatMiaoEvent += new Neighbor().Awake;
                    cat.CatMiaoEvent += new Stealer().Hide;
                    if (true)
                    {
                        AddDog(cat);
                    }

                    cat.MiaoEvent();

                    cat.CatMiaoEvent -= brother.Turn;

                    cat.MiaoEvent();
                }
            }
            {
                Console.WriteLine("*************Another Cat***************");
                Cat cat = new Cat();

                Brother brother = new Brother();

                cat.AddObserver(new Baby());
                cat.AddObserver(new Father());
                cat.AddObserver(new Mother());
                cat.AddObserver(brother);
                cat.AddObserver(new Neighbor());

                cat.MiaoObserver();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Console.Read();
    }
        private void SetLabelWidths(Brother parent, int generations) 
        {
            if( generations < 0 ) return; 

            var count = parent.ChildCount;
            parent.Label.Width = maximumWidth;
            parent.Width = parent.Label.Width;

            for ( var i = 0; i < count; i++ )
            {
                SetLabelWidths( (Brother) parent[i], generations - 1 );
            }
        }
        private void RefreshNoBigListBox(Brother brother)
        {
            if( brother == null ) return;
            
            //if( brother == Root )
            //{
            //    lbNoRelation.Items.Clear();
            //}

            for ( var i = 0; i < brother.ChildCount; i++ )
            {
                var little = (Brother) brother[i];
                if( little == null ) continue;
                
                //if( brother == Root ) 
                //{
                //    if( !lbNoRelation.Items.Contains( little ) )
                //    {
                //        lbNoRelation.Items.Add( little );
                //    }
                //}

                if( !cbTreeParent.Items.Contains( little) )
                {
                    cbTreeParent.Items.Add( little );
                }

                if( !CurrentBrothers.Contains(little.ToString()) )
                {
                    CurrentBrothers.Add( little.ToString() );
                }

                RefreshNoBigListBox( little );
            }
        }
        private void PopulateBrothers(bool isXml)
        {
            if( isXml )
            {
                xmlDocument = new XmlDocument();
                ImportFromXml();
                RefreshNoBigListBox( Root );
            }
            else if( databaseConnection != null )
            {
                var cmd = new MySqlCommand(Util.GetLocalizedString("SQLSelectAllBrothers"), databaseConnection);
                databaseConnection.Open();
                var rdr = cmd.ExecuteReader();
                while ( rdr.Read() )
                {
                    var bigName = rdr.GetString( 4 );
                    var last = rdr.GetString( 0 );
                    var first = rdr.GetString( 1 );
                    var month = rdr.GetString( 2 );
                    var year = rdr.GetInt32( 3 );
                    var space = bigName.LastIndexOf( ' ' );

                    Brother tmpBig;
                    var tmp = Root.FindDescendant( bigName );
                    if( tmp != null )
                    {
                        tmpBig = tmp;
                        if( tmpBig.GetParent() == Root || tmpBig.GetParent() == null && tmpBig != Root ) 
                        {
                            RefreshNoBigListBox( Root );
                        }
                    }
                    else
                    {
                        tmpBig = new Brother( bigName.Substring( space + 1 ), bigName.Substring( 0, space ), Util.DefaultInitiationTerm, Util.DefaultYear )
                        {
                            Label = {ContextMenuStrip = cmNodeActions}
                        };
                        Root.AddChild( tmpBig );
                        RefreshNoBigListBox( Root );
                    }

                    Brother newB;
                    var name = Util.FormatName( first, last );
                    tmp = Root.FindDescendant(name);
                    if( tmp != null )
                    {
                        newB = tmp;
                        if( !newB.HasParent() || newB.GetParent() != tmpBig )
                        {
                            tmpBig.AddChild(newB);
                        }

                        newB.InitiationTerm = Util.StringToInitiationTerm(month);
                        newB.InitiationYear = year;
                    }
                    else
                    {
                        newB = new Brother( last, first, month, year )
                        {
                            Label = {ContextMenuStrip = cmNodeActions}
                        };
                        tmpBig.AddChild( newB );
                    }

                    RefreshNoBigListBox( Root );
                }
                rdr.Close();

                databaseConnection.Close();
            }

            if( Root.HasChild() )
            {
                updwnNumGen.Enabled = true;
                cbTreeParent.Enabled = true;
            }

            cbTreeParent.Sorted = true;
        }
        private void EditBrotherPanel_Apply_onClick(object sender, EventArgs eventArguments)
        {
            if( cbSelectedTerm.SelectedIndex != -1 && ((selectedEdits & FieldEdit.IniMonth) != 0) ) 
            {
                selected.InitiationTerm = Util.StringToInitiationTerm(cbSelectedTerm.SelectedItem.ToString());
            }

            if( (selectedEdits & FieldEdit.IniYear) != 0 )
            {
                selected.InitiationYear = dtpSelectedYear.Value.Year;
            }

            if( (selectedEdits & FieldEdit.Active) != 0 )
            {
                selected.Active = chbActive.Checked;
            }

            if( tbSelectedFirst.Text != string.Empty && ((selectedEdits & FieldEdit.FirstName) != 0) )
            {
                cbTreeParent.Items.Remove( selected );
                selected.FirstName = tbSelectedFirst.Text;
                cbTreeParent.Items.Add( selected );
                cbTreeParent.Sorted = true;
            }

            if( tbSelectedLast.Text != string.Empty && ((selectedEdits & FieldEdit.LastName) != 0) )
            {
                cbTreeParent.Items.Remove( selected );
                selected.LastName = tbSelectedLast.Text;
                cbTreeParent.Items.Add( selected );
                cbTreeParent.Sorted = true;
            }

            if( (selectedEdits & FieldEdit.Big) != 0 )
            {
                if( tbSelectedBig.Text == string.Empty )
                {
                    if( selected.HasParent() )
                    {
                        if( selected != Root )
                        {
                            Root.AddChild( selected );
                        }

                        RefreshNoBigListBox( Root );
                    }
                }
                else
                {
                    var tmp = Root.FindDescendant( tbSelectedBig.Text );
                    if( tmp == null )
                    {
                        var space = tbSelectedBig.Text.LastIndexOf( ' ' );
                        tmp = new Brother( tbSelectedBig.Text.Substring( space + 1 ), tbSelectedBig.Text.Substring( 0, space ), Util.DefaultInitiationTerm, Util.DefaultYear )
                        {
                            Label = {ContextMenuStrip = cmNodeActions}
                        };
                        Root.AddChild( tmp );
                        tmp.AddChild( selected );
                        RefreshNoBigListBox( Root );
                    }
                    else
                    {
                        if( selected.HasParent() ) 
                        {
                            tmp.AddChild( selected );
                        }
                        else
                        {
                            tmp.AddChild( selected );
                        }
                    }
                }
            }

            if( (selectedEdits & FieldEdit.Littles) != 0 )
            {
                if( tbSelectedLittles.Text == string.Empty )
                {
                    for ( var i = 0; i < selected.ChildCount; i ++ ) 
                    {
                        Root.AddChild( (Brother) selected[i] );
                    }

                    RefreshNoBigListBox( Root );
                }
                else
                {
                    for ( var i = 0; i < selected.ChildCount; i++ ) 
                    {
                        Root.AddChild( (Brother) selected[i] );
                    }

                    var littles = tbSelectedLittles.Text.Split( new[] {'\n', '\r'},
                        StringSplitOptions.RemoveEmptyEntries );

                    for ( var i = 0; i < littles.Length; i++ )
                    {
                        var space = littles[0].LastIndexOf( ' ' );
                        var tmp = Root.FindDescendant(littles[0]);
                        Brother littleBrother;
                        if( tmp != null )
                        {
                            littleBrother = tmp;
                            if( littleBrother.HasParent() ) 
                            {
                                selected.AddChild( littleBrother );
                            }
                            else
                            {
                                selected.AddChild( littleBrother );
                                RefreshNoBigListBox( Root );
                            }
                        }
                        else
                        {
                            littleBrother = new Brother(littles[0].Substring(space + 1),
                                littles[0].Substring(0, space),
                                Util.DefaultInitiationTerm, selected.InitiationYear + 1 )
                            {
                                Label = {ContextMenuStrip = cmNodeActions}
                            };
                            selected.AddChild( littleBrother );
                        }
                    }
                }
            }

            if( (selectedEdits & (FieldEdit.IniMonth | FieldEdit.IniYear)) != 0 ) 
            {
                if( selected !=null )
                {
                    ((Brother)selected.GetParent()).RecalculateChildOrder();
                }
            }

            if( treeRoot == selected && cbTreeParent.Text == string.Empty)
            {
                cbTreeParent.SelectedItem = treeRoot;
                EditBrotherPanel_Initalize( treeRoot );
            }
            else
            {
                EditBrotherPanel_Initalize( selected );
            }

            RefreshNoBigListBox( Root );
            cbTreeParent.Sorted = true;
            DisplayTree( true );
        }
        private void Database_WriteBack(Brother currentParent)
        {
            MySqlCommand sqlCommand = null;
            try
            {
                if( databaseConnection == null ) return;

                if( currentParent.HasChild() )
                {
                    Database_WriteBack( (Brother) currentParent.GetFirstChild() );
                }

                if( currentParent.HasRightSibling() ) 
                {
                    Database_WriteBack( (Brother) currentParent.GetRightSibling() );
                }

                if( currentParent == Root ) return; 
               
                databaseConnection.Open();
                sqlCommand = new MySqlCommand(Util.GetLocalizedString("SQLInsertIntoBrothers"), databaseConnection);

                sqlCommand.Prepare();
                sqlCommand.Parameters.AddWithValue( "@Last", currentParent.LastName );
                sqlCommand.Parameters.AddWithValue( "@First", currentParent.FirstName );
                sqlCommand.Parameters.AddWithValue( "@IniMonth", currentParent.InitiationTerm.ToString() );
                sqlCommand.Parameters.AddWithValue( "@IniYear", currentParent.InitiationYear );

                sqlCommand.Parameters.AddWithValue( "@Big",
                    currentParent.HasParent() 
                        ? ((Brother) currentParent.GetParent()).ToString() 
                        : string.Empty );

                sqlCommand.Parameters.AddWithValue( "@NextSibling",
                    currentParent.HasRightSibling()
                        ? ((Brother) currentParent.GetRightSibling()).ToString()
                        : string.Empty );

                sqlCommand.Parameters.AddWithValue( "@FirstLittle", 
                    currentParent.HasChild() 
                        ? ((Brother) currentParent.GetFirstChild()).ToString() 
                        : string.Empty );

                sqlCommand.ExecuteNonQuery();
                databaseConnection.Close();
            }
            catch ( Exception exception )
            {
                var message = exception.Message;

                if( sqlCommand != null )
                {
                    message += '\n';
                    message += sqlCommand.CommandText;
                }

                MessageBox.Show(message);
            }
        }
 public void Circularity()
 {
     Brother emmanuel = new Brother();
     emmanuel.Name = "Emmanuel";
     Address.blacklistedZipCode = "666";
     Address address = new Address();
     address.InternalValid = true;
     address.Country = "France";
     address.Id = 3;
     address.Line1 = "Rue des rosiers";
     address.State = "NYC";
     address.Zip = "33333";
     address.floor = 4;
     emmanuel.Address = address;
     Brother christophe = new Brother();
     christophe.Name = "Christophe";
     christophe.Address = address;
     emmanuel.YoungerBrother = christophe;
     christophe.Elder = emmanuel;
     IClassValidator classValidator = GetClassValidator(typeof(Brother));
     InvalidValue[] invalidValues = classValidator.GetInvalidValues(emmanuel);
     Assert.AreEqual(0, invalidValues.Length);
     christophe.Name = null;
     invalidValues = classValidator.GetInvalidValues(emmanuel);
     Assert.AreEqual(1, invalidValues.Length, "Name cannot be null");
     Assert.AreEqual(emmanuel, invalidValues[0].RootEntity);
     Assert.AreEqual("YoungerBrother.Name", invalidValues[0].PropertyPath);
     christophe.Name = "Christophe";
     address = new Address();
     address.InternalValid = true;
     address.Country = "France";
     address.Id = 4;
     address.Line1 = "Rue des plantes";
     address.State = "NYC";
     address.Zip = "33333";
     address.floor = -100;
     christophe.Address = address;
     invalidValues = classValidator.GetInvalidValues(emmanuel);
     Assert.AreEqual(1, invalidValues.Length, "Floor cannot be less than -2");
 }
        private Brother ConvertXmlToTree(XmlNode currentParent)
        {
            if( currentParent == null ) return null;
            if( currentParent.Attributes == null ) return null;
            
            var big = new Brother( currentParent.Attributes["Last"].Value,
                currentParent.Attributes["First"].Value,
                currentParent.Attributes["IniTerm"].Value,
                int.Parse( currentParent.Attributes["IniYear"].Value ) )
            {
                Active = Util.ConvertStringToBool( currentParent.Attributes["Active"].Value ),
                Label = {ContextMenuStrip = cmNodeActions}
            };

            ttTree.SetToolTip(big.Label, Util.GetLocalizedString("LeftClickSelectEdit")); 

            foreach ( XmlNode child in currentParent.ChildNodes )
            {
                big.AddChild( ConvertXmlToTree( child ) );
            }

            return big;
        }