public FormCreatureViewEdit(
            [NotNull] FormGrangerMain mainForm,
            [NotNull] GrangerContext context,
            [NotNull] ILogger logger,
            [NotNull] IWurmApi wurmApi,
            [CanBeNull] Creature creature,
            CreatureViewEditOpType optype,
            string herdId,
            [NotNull] CreatureColorDefinitions creatureColorDefinitions)
        {
            if (mainForm == null)
            {
                throw new ArgumentNullException(nameof(mainForm));
            }
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (wurmApi == null)
            {
                throw new ArgumentNullException(nameof(wurmApi));
            }
            if (creatureColorDefinitions == null)
            {
                throw new ArgumentNullException(nameof(creatureColorDefinitions));
            }
            this.mainForm = mainForm;
            this.creature = creature;
            this.context  = context;
            this.herdId   = herdId;
            this.creatureColorDefinitions = creatureColorDefinitions;
            this.logger  = logger;
            this.wurmApi = wurmApi;
            InitializeComponent();

            DisableAllFields();

            comboBoxServerName.Items.AddRange(
                wurmApi.Servers.All.Select(server => server.ServerName.Original).Cast <object>().ToArray());

            List <string> list = new List <string>();

            list.AddRange(this.context.Creatures.Select(x => x.Name));
            list.AddRange(this.context.Creatures.Select(x => x.MotherName));
            list.AddRange(this.context.Creatures.Select(x => x.FatherName));

            var allCreatureNamesInDatabase = list.Distinct().Where(x => x != null).Cast <object>().ToArray();

            comboBoxFather.Items.AddRange(allCreatureNamesInDatabase);
            comboBoxMother.Items.AddRange(allCreatureNamesInDatabase);
            ;
            comboBoxColor.Items.AddRange(
                creatureColorDefinitions.GetColors().Select(color => color.CreatureColorId).Cast <object>().ToArray());
            comboBoxColor.Text = CreatureColor.GetDefaultColor().CreatureColorId;
            comboBoxAge.Items.AddRange(CreatureAge.GetColorsEnumStrArray().Cast <object>().ToArray());
            comboBoxAge.Text = CreatureAge.GetDefaultAgeStr();

            this.OpMode = optype;
        }
        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (!ValidateCreatureIdentity())
            {
                this.DialogResult = System.Windows.Forms.DialogResult.None;
            }
            else
            {
                try
                {
                    if (OpMode == CreatureViewEditOpType.New)
                    {
                        var newEntity = new CreatureEntity()
                        {
                            Id = CreatureEntity.GenerateNewCreatureId(context)
                        };
                        creature = new Creature(mainForm, newEntity, context, creatureColorDefinitions);
                    }

                    List <CreatureTrait> traitlist = new List <CreatureTrait>();
                    foreach (var item in checkedListBoxTraits.CheckedItems)
                    {
                        try
                        {
                            traitlist.Add(CreatureTrait.FromWurmTextRepr(item.ToString()));
                        }
                        catch (Exception _e)
                        {
                            logger.Error(_e, "failed to create creature trait from text:" + item.ToString());
                        }
                    }
                    var traitlistArray = traitlist.ToArray();

                    creature.Name          = textBoxName.Text.Trim();
                    creature.Father        = comboBoxFather.Text.Trim();
                    creature.Mother        = comboBoxMother.Text.Trim();
                    creature.TakenCareOfBy = textBoxCaredForBy.Text.Trim();
                    creature.BrandedFor    = textBoxBrandedFor.Text.Trim();

                    creature.Traits = traitlistArray;

                    creature.TraitsInspectSkill = (float)numericUpDownAHskill.Value;
                    float traitSkill = CreatureTrait.GetMinSkillForTraits(traitlistArray, checkBoxEpic.Checked);
                    if (creature.TraitsInspectSkill < traitSkill)
                    {
                        creature.TraitsInspectSkill = traitSkill;
                    }
                    creature.EpicCurve = checkBoxEpic.Checked;

                    creature.Comments = textBoxComment.Text;
                    creature.IsMale   = radioButtonMale.Checked;
                    creature.Color    = creatureColorDefinitions.GetForId(comboBoxColor.Text);
                    creature.Age      = CreatureAge.CreateAgeFromEnumString(comboBoxAge.Text);

                    creature.NotInMoodUntil = dateTimePickerBred.Value;
                    creature.GroomedOn      = dateTimePickerGroomed.Value;
                    creature.PregnantUntil  = dateTimePickerPregnant.Value;
                    creature.BirthDate      = dateTimePickerBirthDate.Value;

                    creature.SetTag("diseased", checkBoxDiseased.Checked);
                    creature.SetTag("dead", checkBoxDead.Checked);
                    creature.SetTag("sold", checkBoxSold.Checked);

                    creature.ServerName = comboBoxServerName.Text.Trim();

                    if (OpMode == CreatureViewEditOpType.New)
                    {
                        creature.Herd = herdId;
                        context.InsertCreature(creature.Entity);
                    }
                    else
                    {
                        context.SubmitChanges();
                    }
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                }
                catch (Exception _e)
                {
                    logger.Error(_e, "problem while updating database, op: " + OpMode);
                    MessageBox.Show("There was a problem on submitting to database.\r\n" + _e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.DialogResult = System.Windows.Forms.DialogResult.None;
                }
            }
        }
Esempio n. 3
0
 public static CreatureAge ExtractCreatureAge(string prefixedObjectName)
 {
     return(CreatureAge.CreateAgeFromRawCreatureNameStartsWith(prefixedObjectName));
 }
        public void HandleLogEvent(string line)
        {
            // Smile emote triggers processing of new creature.
            // If previous processing is still active, it should be finalized.
            if (line.StartsWith("You smile at", StringComparison.Ordinal))
            {
                debugLogger.Log("smile cond: " + line);
                AttemptToStartProcessing(line);
            }

            // While processing creature, log events are parsed and valid data buffered into the current buffer.
            if (isProcessing)
            {
                //[20:23:18] It has fleeter movement than normal. It has a strong body. It has lightning movement. It can carry more than average. It seems overly aggressive.
                if (!verifyList.Traits && CreatureTrait.CanThisBeTraitLogMessage(line))
                {
                    debugLogger.Log("found maybe trait line: " + line);
                    var extractedTraits = GrangerHelpers.ParseTraitsFromLine(line);
                    foreach (var trait in extractedTraits)
                    {
                        debugLogger.Log("found trait: " + trait);
                        creatureBuffer.Traits.Add(trait);
                        verifyList.Traits = true;
                    }
                    debugLogger.Log("trait parsing finished");
                    if (creatureBuffer.InspectSkill == 0 && creatureBuffer.Traits.Count > 0)
                    {
                        var message =
                            String.Format(
                                "{0} ({1}) can see traits, but Granger found no Animal Husbandry skill for him. Is this a bug? Creature will be added anyway.",
                                playerMan.PlayerName, creatureBuffer.Server);
                        logger.Error(message);
                        trayPopups.Schedule(message, "POSSIBLE PROBLEM", 5000);
                    }
                }
                //[20:23:18] She is very strong and has a good reserve of fat.
                if (line.StartsWith("He", StringComparison.Ordinal) && !verifyList.Gender)
                {
                    creatureBuffer.IsMale = true;
                    verifyList.Gender     = true;
                    debugLogger.Log("creature set to male");
                }
                if (line.StartsWith("She", StringComparison.Ordinal) && !verifyList.Gender)
                {
                    creatureBuffer.IsMale = false;
                    verifyList.Gender     = true;
                    debugLogger.Log("creature set to female");
                }
                //[22:34:28] His mother is the old fat Painthop. His father is the venerable fat Starkclip.
                //[22:34:28] Her mother is the old fat Painthop. Her father is the venerable fat Starkclip.
                if (IsParentIdentifyingLine(line) && !verifyList.Parents)
                {
                    debugLogger.Log("found maybe parents line");

                    Match motherMatch = ParseMother(line);
                    if (motherMatch.Success)
                    {
                        string mother = motherMatch.Groups["g"].Value;
                        mother = GrangerHelpers.ExtractCreatureName(mother);
                        creatureBuffer.MotherName = mother;
                        debugLogger.Log("mother set to: " + mother);
                    }
                    Match fatherMatch = ParseFather(line);
                    if (fatherMatch.Success)
                    {
                        string father = fatherMatch.Groups["g"].Value;
                        father = GrangerHelpers.ExtractCreatureName(father);
                        creatureBuffer.FatherName = father;
                        debugLogger.Log("father set to: " + father);
                    }
                    verifyList.Parents = true;
                    debugLogger.Log("finished parsing parents line");
                }
                //[20:23:18] It is being taken care of by Darkprincevale.
                if (line.Contains("It is being taken care") && !verifyList.CaredBy)
                {
                    debugLogger.Log("found maybe take care of line");
                    Match caredby = Regex.Match(line, @"care of by (\w+)");
                    if (caredby.Success)
                    {
                        creatureBuffer.CaredBy = caredby.Groups[1].Value;
                        debugLogger.Log("cared set to: " + creatureBuffer.CaredBy);
                    }
                    verifyList.CaredBy = true;
                    debugLogger.Log("finished parsing care line");
                }
                //[17:11:42] She will deliver in about 4 days.
                //[17:11:42] She will deliver in about 1 day.
                if (line.Contains("She will deliver in") && !verifyList.Pregnant)
                {
                    debugLogger.Log("found maybe pregnant line");
                    Match match = Regex.Match(line, @"She will deliver in about (\d+)");
                    if (match.Success)
                    {
                        double length = Double.Parse(match.Groups[1].Value) + 1D;
                        creatureBuffer.PregnantUntil = DateTime.Now + TimeSpan.FromDays(length);
                        debugLogger.Log("found creature to be pregnant, estimated delivery: " + creatureBuffer.PregnantUntil);
                    }
                    verifyList.Pregnant = true;
                    debugLogger.Log("finished parsing pregnant line");
                }
                //[20:58:26] A foal skips around here merrily
                //[01:59:09] This calf looks happy and free.
                if ((line.Contains("A foal skips around here merrily") ||
                     line.Contains("This calf looks happy and free") ||
                     line.Contains("A small cuddly ball of fluff")) &&
                    !verifyList.Foalization)
                {
                    debugLogger.Log("applying foalization to the creature");
                    try
                    {
                        creatureBuffer.Age     = CreatureAge.Foalize(creatureBuffer.Age);
                        verifyList.Foalization = true;
                    }
                    catch (InvalidOperationException exception)
                    {
                        logger.Error(exception, "The creature appears to be a foal, but has invalid age for a foal!");
                    }
                }
                //[20:57:27] It has been branded by and belongs to the settlement of Silver Hill Estate.
                if (line.Contains("It has been branded") && !verifyList.Branding)
                {
                    debugLogger.Log("found maybe branding line");
                    Match match = Regex.Match(line, @"belongs to the settlement of (.+)\.");
                    if (match.Success)
                    {
                        string settlementName = match.Groups[1].Value;
                        creatureBuffer.BrandedBy = settlementName;
                        debugLogger.Log("found creature to be branded for: " + creatureBuffer.BrandedBy);
                        verifyList.Branding = true;
                    }
                }
                //[11:43:35] Its colour is ash.
                if (line.Contains("Its colour is"))
                {
                    debugLogger.Log("found maybe color line");
                    Match match = Regex.Match(line, @"Its colour is (.+)\.");
                    if (match.Success)
                    {
                        string colorName = match.Groups[1].Value;
                        creatureBuffer.ColorWurmLogText = colorName;
                        debugLogger.Log("found creature to have color: " + creatureBuffer.ColorWurmLogText);
                        verifyList.Branding = true;
                    }
                }
            }
        }
        /// <returns></returns>
        CreatureData GetCreatureDataFromAnyLogEvent(string line, bool searchEntireDb)
        {
            var creaturesQuery = context.Creatures;

            if (!searchEntireDb)
            {
                var selectedHerds = context.Herds.Where(x => x.Selected).Select(x => x.HerdId).ToArray();
                creaturesQuery = creaturesQuery.Where(x => selectedHerds.Contains(x.Herd)).ToArray();
            }

            if (UseServerAsCreatureId)
            {
                var server = playerManager.CurrentServer;
                if (server == null)
                {
                    logger.Info(
                        "GetCreatureDataFromAnyLogEvent skipped processing log line, " +
                        "due to unknown current server and UseServerAsCreatureId is enabled.");
                    creaturesQuery = new CreatureEntity[0];
                }
                else
                {
                    creaturesQuery =
                        creaturesQuery.Where(
                            entity =>
                            string.IsNullOrEmpty(entity.ServerName) || server.ServerName.Matches(entity.ServerName));
                }
            }

            var filteredCreatures = creaturesQuery.Where(x => line.Contains(x.Name, StringComparison.OrdinalIgnoreCase)).ToArray();

            var result = new CreatureData();

            foreach (CreatureEntity creatureEntity in filteredCreatures)
            {
                result.SecondaryInfo = null;
                Match match = Regex.Match(line, @"(\w+) (\w+) " + creatureEntity.Name, RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    result.Age = CreatureAge.CreateAgeFromRawCreatureName(match.Groups[1].Value);
                    if (result.Age.CreatureAgeId != CreatureAgeId.Unknown)
                    {
                        result.SecondaryInfo = match.Groups[2].Value;
                    }
                    else
                    {
                        match = Regex.Match(line, @"(\w+) " + creatureEntity.Name, RegexOptions.IgnoreCase);
                        if (match.Success)
                        {
                            result.Age = CreatureAge.CreateAgeFromRawCreatureName(match.Groups[1].Value);
                            if (result.Age.CreatureAgeId != CreatureAgeId.Unknown)
                            {
                                result.SecondaryInfo = String.Empty;
                            }
                        }
                    }
                    if (result.Age.CreatureAgeId != CreatureAgeId.Unknown)
                    {
                        result.Creature = creatureEntity;

                        // Attempting to advance age, unless it's ambiguous.
                        var prevAge = result.Creature.Age.CreatureAgeId;
                        var newAge  = result.Age.CreatureAgeId;

                        if (prevAge == CreatureAgeId.YoungFoal)
                        {
                            // Ambiguous: young foal or young mature, keep old value
                            if (newAge == CreatureAgeId.Young)
                            {
                                result.Age = new CreatureAge(prevAge);
                            }
                            // Ambiguous: adolescent foal or adolescent mature, keep old value
                            if (newAge == CreatureAgeId.Adolescent)
                            {
                                result.Age = new CreatureAge(prevAge);
                            }
                        }
                        if (prevAge == CreatureAgeId.AdolescentFoal)
                        {
                            // Acceptable: young in this context can only mean young mature
                            if (newAge == CreatureAgeId.Young)
                            {
                                result.Age = new CreatureAge(CreatureAgeId.Young);
                            }
                            // Ambiguous: adolescent foal or adolescent mature, keep old value
                            if (newAge == CreatureAgeId.Adolescent)
                            {
                                result.Age = new CreatureAge(prevAge);
                            }
                        }

                        break;
                    }
                }
            }

            if (result.Creature == null)
            {
                return(null);
            }
            var existingCreaturesInQuery = filteredCreatures.Where(x => x.Name == result.Creature.Name).ToArray();

            if (existingCreaturesInQuery.Length == 1)
            {
                return(result);
            }
            else if (existingCreaturesInQuery.Length > 1)
            {
                result.TooManyCreaturesFound = true;
                return(result);
            }
            return(null);
        }
Esempio n. 6
0
        public void ImportHerd(GrangerContext context, string newHerdName, string xmlFilePath)
        {
            if (newHerdName == null || newHerdName.Trim() == string.Empty)
            {
                throw new GrangerException("new herd name cannot be empty");
            }

            // check if this herd already exists in database
            if (context.Herds.Any(x => x.HerdId == newHerdName))
            {
                throw new GrangerException($"there is already a herd with named {newHerdName} in database");
            }

            XDocument doc = XDocument.Load(xmlFilePath);
            var       creatureEntities = new List <CreatureEntity>();
            var       elements         = doc.Root.Elements("Horse").Union(doc.Root.Elements("Creature"));

            foreach (var x in elements)
            {
                var entity = new CreatureEntity();
                entity.Herd = newHerdName;
                entity.Name = x.Element("Name").Value;

                if (creatureEntities.Any(y => y.Name.Equals(entity.Name, StringComparison.InvariantCultureIgnoreCase)))
                {
                    throw new GrangerException(
                              $"Creature named {entity.Name} was already added from this XML file. Review the file for any errors.");
                }

                entity.FatherName = x.Element("Father").Value;
                entity.MotherName = x.Element("Mother").Value;
                entity.Traits     = GetTraitsFromXML(x.Element("Traits"));

                var notInMood = x.Element("NotInMoodUntil").Value;
                if (string.IsNullOrEmpty(notInMood))
                {
                    entity.NotInMood = null;
                }
                else
                {
                    entity.NotInMood = DateTime.Parse(notInMood, CultureInfo.InvariantCulture);
                }

                var pregnantUntil = x.Element("PregnantUntil").Value;
                if (string.IsNullOrEmpty(pregnantUntil))
                {
                    entity.PregnantUntil = null;
                }
                else
                {
                    entity.PregnantUntil = DateTime.Parse(pregnantUntil, CultureInfo.InvariantCulture);
                }

                var groomedOn = x.Element("GroomedOn").Value;
                if (string.IsNullOrEmpty(groomedOn))
                {
                    entity.GroomedOn = null;
                }
                else
                {
                    entity.GroomedOn = DateTime.Parse(groomedOn, CultureInfo.InvariantCulture);
                }

                var gender = x.Element("Gender").Value;
                if (string.IsNullOrEmpty(gender))
                {
                    entity.IsMale = null;
                }
                else
                {
                    entity.IsMale = gender.Equals("male", StringComparison.InvariantCultureIgnoreCase);
                }

                entity.TakenCareOfBy = x.Element("CaredBy").Value;

                var xInspect = x.Element("InspectSkill");
                if (string.IsNullOrEmpty(xInspect.Value))
                {
                    entity.TraitsInspectedAtSkill = null;
                }
                else
                {
                    entity.TraitsInspectedAtSkill = float.Parse(xInspect.Value, CultureInfo.InvariantCulture);
                }
                var xInspectAttr = xInspect.Attribute("IsEpic");
                if (string.IsNullOrEmpty(xInspectAttr.Value))
                {
                    entity.EpicCurve = null;
                }
                else
                {
                    entity.EpicCurve = bool.Parse(xInspectAttr.Value);
                }

                entity.Age             = CreatureAge.CreateAgeFromEnumString(x.Element("Age").Value);
                entity.CreatureColorId = x.Element("CreatureColorId")?.Value ?? CreatureColorEntity.Unknown.Id;
                entity.Comments        = x.Element("Comments").Value;
                entity.SpecialTagsRaw  = x.Element("Tags").Value;
                entity.BrandedFor      = x.Element("BrandedFor").Value;
                var smilexaminedElement = x.Element("SmilexamineLastDate");
                if (smilexaminedElement != null && !string.IsNullOrWhiteSpace(smilexaminedElement.Value))
                {
                    entity.SmilexamineLastDate = DateTime.Parse(smilexaminedElement.Value, CultureInfo.InvariantCulture);
                }

                var serverNameElem = x.Element("ServerName");
                entity.ServerName = serverNameElem?.Value;

                creatureEntities.Add(entity);
            }

            context.InsertHerd(newHerdName);
            foreach (var creatureEntity in creatureEntities)
            {
                creatureEntity.Id = CreatureEntity.GenerateNewCreatureId(context);
                context.InsertCreature(creatureEntity);
            }
        }