Beispiel #1
0
        private void frmUpdate_Load(object sender, EventArgs e)
        {
            if (!_blnIsConnected)
            {
                Close();
                return;
            }
            Log.Info("frmUpdate_Load enter");
            Log.Info("Check Global Mutex for duplicate");
            bool blnHasDuplicate;

            try
            {
                blnHasDuplicate = !Program.GlobalChummerMutex.WaitOne(0, false);
            }
            catch (AbandonedMutexException ex)
            {
                Log.Error(ex);
                Utils.BreakIfDebug();
                blnHasDuplicate = true;
            }
            Log.Info("blnHasDuplicate = " + blnHasDuplicate.ToString(GlobalOptions.InvariantCultureInfo));
            // If there is more than 1 instance running, do not let the application be updated.
            if (blnHasDuplicate)
            {
                Log.Info("More than one instance, exiting");
                if (!SilentMode)
                {
                    Program.MainForm.ShowMessageBox(this, LanguageManager.GetString("Message_Update_MultipleInstances"), LanguageManager.GetString("Title_Update"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                Log.Info("frmUpdate_Load exit");
                Close();
            }
            if (!_blnChangelogDownloaded && !_workerConnectionLoader.IsBusy)
            {
                _workerConnectionLoader.RunWorkerAsync();
            }
            Log.Info("frmUpdate_Load exit");
        }
        public static object EvaluateInvariantXPath(string strXPath, out bool blnIsSuccess)
        {
            if (!strXPath.IsLegalCharsOnly(true, s_LstInvariantXPathLegalChars))
            {
                blnIsSuccess = false;
                return(strXPath);
            }

            object objReturn;

            try
            {
                objReturn    = s_ObjXPathNavigator.Evaluate(strXPath);
                blnIsSuccess = true;
            }
            catch (Exception)
            {
                Utils.BreakIfDebug();
                objReturn    = strXPath;
                blnIsSuccess = false;
            }
            return(objReturn);
        }
Beispiel #3
0
        /// <summary>
        /// Accept the selected item and close the form.
        /// </summary>
        private void AcceptForm()
        {
            XmlNode objXmlLifestyle = _objXmlDocument.SelectSingleNode("/chummer/lifestyles/lifestyle[name = \"" + cboLifestyle.SelectedValue + "\"]");

            _objLifestyle.Source        = objXmlLifestyle["source"].InnerText;
            _objLifestyle.Page          = objXmlLifestyle["page"].InnerText;
            _objLifestyle.Name          = txtLifestyleName.Text;
            _objLifestyle.BaseLifestyle = cboLifestyle.SelectedValue.ToString();
            _objLifestyle.Cost          = Convert.ToDecimal(objXmlLifestyle["cost"].InnerText, GlobalOptions.InvariantCultureInfo);
            _objLifestyle.Roommates     = _objLifestyle.TrustFund ? 0 : decimal.ToInt32(nudRoommates.Value);
            _objLifestyle.Percentage    = nudPercentage.Value;
            _objLifestyle.LifestyleQualities.Clear();
            _objLifestyle.StyleType  = _objType;
            _objLifestyle.Dice       = Convert.ToInt32(objXmlLifestyle["dice"].InnerText);
            _objLifestyle.Multiplier = Convert.ToDecimal(objXmlLifestyle["multiplier"].InnerText, GlobalOptions.InvariantCultureInfo);

            if (objXmlLifestyle.TryGetField("id", Guid.TryParse, out Guid source))
            {
                _objLifestyle.SourceID = source;
            }
            else
            {
                Log.Warning(new object[] { "Missing id field for lifestyle xmlnode", objXmlLifestyle });
                Utils.BreakIfDebug();
            }
            foreach (TreeNode objNode in treQualities.Nodes)
            {
                if (objNode.Checked)
                {
                    XmlNode          objXmlLifestyleQuality = _objXmlDocument.SelectSingleNode($"/chummer/qualities/quality[id = \"{objNode.Tag}\"]");
                    LifestyleQuality objQuality             = new LifestyleQuality(_objCharacter);
                    objQuality.Create(objXmlLifestyleQuality, _objLifestyle, _objCharacter, QualitySource.Selected, objNode.Text);
                    _objLifestyle.LifestyleQualities.Add(objQuality);
                }
            }
            DialogResult = DialogResult.OK;
        }
Beispiel #4
0
        public void Dispose()
        {
            if (_blnDisposed)
            {
                return;
            }
            _blnDisposed = true;
            if (_objControl == null)
            {
                lock (_intApplicationWaitCursorsLock)
                {
                    _intApplicationWaitCursors -= 1;
                    if (_intApplicationWaitCursors <= 0)
                    {
                        Application.UseWaitCursor = false;
                    }
                }
                return;
            }
            Log.Trace("CursorWait for Control \"" + _objControl + "\" disposing with Guid \"" + instance.ToString() + "\" after " + objTimer.ElapsedMilliseconds + "ms.");
            objTimer.Stop();
            if (!_dicWaitingControls.TryGetValue(_objControl, out ConcurrentStack <CursorWait> stkCursorWaits) || stkCursorWaits == null || stkCursorWaits.Count <= 0)
            {
                Utils.BreakIfDebug();
                Log.Error("CursorWait for Control \"" + _objControl + "\" with Guid \"" + instance.ToString() + "\" somehow does not have a CursorWait stack defined for it");
                throw new ArgumentNullException(nameof(stkCursorWaits));
            }
            CursorWait objPoppedCursorWait = stkCursorWaits.Pop();

            if (objPoppedCursorWait != this)
            {
                Utils.BreakIfDebug();
                Log.Error("CursorWait for Control \"" + _objControl + "\" with Guid \"" + instance.ToString() + "\" somehow does not have a CursorWait stack defined for it");
                throw new ArgumentNullException(nameof(objPoppedCursorWait));
            }
            SetControlCursor(stkCursorWaits.Peek()?.CursorToUse);
        }
        private void FinishGenerateOutput(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!e.Cancelled)
            {
                cmdPrint.Enabled       = true;
                tsPrintPreview.Enabled = true;
                tsSaveAsHtml.Enabled   = true;
                cmdSaveAsPdf.Enabled   = true;
            }

            if (GlobalOptions.PrintToFileFirst)
            {
                try
                {
                    File.Delete(_strFilePathName);
                }
                catch (IOException)
                {
                    Utils.BreakIfDebug();
                }
            }

            Cursor = Cursors.Default;
        }
Beispiel #6
0
        /// Create a Martial Art from an XmlNode.
        /// <param name="objXmlArtNode">XmlNode to create the object from.</param>
        public void Create(XmlNode objXmlArtNode)
        {
            if (!objXmlArtNode.TryGetField("id", Guid.TryParse, out _guiSourceID))
            {
                Log.Warn(new object[] { "Missing id field for xmlnode", objXmlArtNode });
                Utils.BreakIfDebug();
            }
            if (objXmlArtNode.TryGetStringFieldQuickly("name", ref _strName))
            {
                _objCachedMyXmlNode = null;
            }
            objXmlArtNode.TryGetStringFieldQuickly("source", ref _strSource);
            objXmlArtNode.TryGetStringFieldQuickly("page", ref _strPage);
            objXmlArtNode.TryGetInt32FieldQuickly("cost", ref _intKarmaCost);
            if (!objXmlArtNode.TryGetStringFieldQuickly("altnotes", ref _strNotes))
            {
                objXmlArtNode.TryGetStringFieldQuickly("notes", ref _strNotes);
            }
            _blnIsQuality = objXmlArtNode["isquality"]?.InnerText == bool.TrueString;

            if (objXmlArtNode["bonus"] != null)
            {
                ImprovementManager.CreateImprovements(_objCharacter, Improvement.ImprovementSource.MartialArt, InternalId,
                                                      objXmlArtNode["bonus"], false, 1, DisplayNameShort(GlobalOptions.Language));
            }

            /*
             * if (string.IsNullOrEmpty(_strNotes))
             * {
             *  _strNotes = CommonFunctions.GetTextFromPDF($"{_strSource} {_strPage}", _strName);
             *  if (string.IsNullOrEmpty(_strNotes))
             *  {
             *      _strNotes = CommonFunctions.GetTextFromPDF($"{Source} {Page(GlobalOptions.Language)}", DisplayName(GlobalOptions.Language));
             *  }
             * }*/
        }
Beispiel #7
0
        /// Create a Martial Art Technique from an XmlNode.
        /// <param name="xmlTechniqueDataNode">XmlNode to create the object from.</param>
        public void Create(XmlNode xmlTechniqueDataNode)
        {
            if (!xmlTechniqueDataNode.TryGetField("id", Guid.TryParse, out _guiSourceID))
            {
                Log.Warn(new object[] { "Missing id field for xmlnode", xmlTechniqueDataNode });
                Utils.BreakIfDebug();
            }

            if (xmlTechniqueDataNode.TryGetStringFieldQuickly("name", ref _strName) && !xmlTechniqueDataNode.TryGetMultiLineStringFieldQuickly("altnotes", ref _strNotes))
            {
                xmlTechniqueDataNode.TryGetMultiLineStringFieldQuickly("notes", ref _strNotes);
            }

            string sNotesColor = ColorTranslator.ToHtml(ColorManager.HasNotesColor);

            xmlTechniqueDataNode.TryGetStringFieldQuickly("notesColor", ref sNotesColor);
            _colNotes = ColorTranslator.FromHtml(sNotesColor);

            xmlTechniqueDataNode.TryGetStringFieldQuickly("source", ref _strSource);
            xmlTechniqueDataNode.TryGetStringFieldQuickly("page", ref _strPage);
            if (string.IsNullOrEmpty(Notes))
            {
                Notes = CommonFunctions.GetBookNotes(xmlTechniqueDataNode, Name, CurrentDisplayName, Source, Page,
                                                     DisplayPage(GlobalSettings.Language), _objCharacter);
            }

            if (xmlTechniqueDataNode["bonus"] == null)
            {
                return;
            }
            if (!ImprovementManager.CreateImprovements(_objCharacter, Improvement.ImprovementSource.MartialArtTechnique,
                                                       _guiID.ToString("D", GlobalSettings.InvariantCultureInfo), xmlTechniqueDataNode["bonus"], 1, CurrentDisplayName))
            {
                _guiID = Guid.Empty;
            }
        }
Beispiel #8
0
 /// Create a Complex Form from an XmlNode.
 /// <param name="objXmlComplexFormNode">XmlNode to create the object from.</param>
 /// <param name="strExtra">Value to forcefully select for any ImprovementManager prompts.</param>
 public void Create(XmlNode objXmlComplexFormNode, string strExtra = "")
 {
     if (!objXmlComplexFormNode.TryGetField("id", Guid.TryParse, out _guiSourceID))
     {
         Log.Warn(new object[] { "Missing id field for complex form xmlnode", objXmlComplexFormNode });
         Utils.BreakIfDebug();
     }
     objXmlComplexFormNode.TryGetField("id", Guid.TryParse, out _guiSourceID);
     objXmlComplexFormNode.TryGetStringFieldQuickly("name", ref _strName);
     objXmlComplexFormNode.TryGetStringFieldQuickly("target", ref _strTarget);
     objXmlComplexFormNode.TryGetStringFieldQuickly("source", ref _strSource);
     objXmlComplexFormNode.TryGetStringFieldQuickly("page", ref _strPage);
     objXmlComplexFormNode.TryGetStringFieldQuickly("duration", ref _strDuration);
     objXmlComplexFormNode.TryGetStringFieldQuickly("fv", ref _strFV);
     if (!objXmlComplexFormNode.TryGetMultiLineStringFieldQuickly("altnotes", ref _strNotes))
     {
         objXmlComplexFormNode.TryGetMultiLineStringFieldQuickly("notes", ref _strNotes);
     }
     if (objXmlComplexFormNode["bonus"] != null)
     {
         ImprovementManager.ForcedValue = strExtra;
         if (!ImprovementManager.CreateImprovements(_objCharacter, Improvement.ImprovementSource.Spell, _guiID.ToString("D", GlobalOptions.InvariantCultureInfo), objXmlComplexFormNode["bonus"], 1, CurrentDisplayName))
         {
             _guiID = Guid.Empty;
             return;
         }
         if (!string.IsNullOrEmpty(ImprovementManager.SelectedValue))
         {
             _strExtra = ImprovementManager.SelectedValue;
         }
     }
     else
     {
         _strExtra = strExtra;
     }
 }
Beispiel #9
0
        /// <summary>
        /// Create a Mentor Spirit from an XmlNode.
        /// </summary>
        /// <param name="xmlMentor">XmlNode to create the object from.</param>
        /// <param name="eMentorType">Whether this is a Mentor or a Paragon.</param>
        /// <param name="strForceValueChoice1">Name/Text for Choice 1.</param>
        /// <param name="strForceValueChoice2">Name/Text for Choice 2.</param>
        /// <param name="strForceValue">Force a value to be selected for the Mentor Spirit.</param>
        public void Create(XmlNode xmlMentor, Improvement.ImprovementType eMentorType, string strForceValue = "", string strForceValueChoice1 = "", string strForceValueChoice2 = "")
        {
            _eMentorType        = eMentorType;
            _objCachedMyXmlNode = null;
            xmlMentor.TryGetStringFieldQuickly("name", ref _strName);
            xmlMentor.TryGetStringFieldQuickly("source", ref _strSource);
            xmlMentor.TryGetStringFieldQuickly("page", ref _strPage);
            if (!xmlMentor.TryGetStringFieldQuickly("altnotes", ref _strNotes))
            {
                xmlMentor.TryGetStringFieldQuickly("notes", ref _strNotes);
            }
            if (!xmlMentor.TryGetField("id", Guid.TryParse, out _guiSourceID))
            {
                Log.Warn(new object[] { "Missing id field for xmlnode", xmlMentor });
                Utils.BreakIfDebug();
            }

            // Build the list of advantages gained through the Mentor Spirit.
            if (!xmlMentor.TryGetStringFieldQuickly("altadvantage", ref _strAdvantage))
            {
                xmlMentor.TryGetStringFieldQuickly("advantage", ref _strAdvantage);
            }
            if (!xmlMentor.TryGetStringFieldQuickly("altdisadvantage", ref _strDisadvantage))
            {
                xmlMentor.TryGetStringFieldQuickly("disadvantage", ref _strDisadvantage);
            }

            _nodBonus = xmlMentor["bonus"];
            if (_nodBonus != null)
            {
                string strOldForce    = ImprovementManager.ForcedValue;
                string strOldSelected = ImprovementManager.SelectedValue;
                ImprovementManager.ForcedValue = strForceValue;
                if (!ImprovementManager.CreateImprovements(_objCharacter, Improvement.ImprovementSource.MentorSpirit, _guiID.ToString("D"), _nodBonus, false, 1, DisplayNameShort(GlobalOptions.Language)))
                {
                    _guiID = Guid.Empty;
                    return;
                }
                _strExtra = ImprovementManager.SelectedValue;
                ImprovementManager.ForcedValue   = strOldForce;
                ImprovementManager.SelectedValue = strOldSelected;
            }
            else if (!string.IsNullOrEmpty(strForceValue))
            {
                _strExtra = strForceValue;
            }
            _nodChoice1 = xmlMentor.SelectSingleNode("choices/choice[name = \"" + strForceValueChoice1 + "\"]/bonus");
            if (_nodChoice1 != null)
            {
                string strOldForce    = ImprovementManager.ForcedValue;
                string strOldSelected = ImprovementManager.SelectedValue;
                //ImprovementManager.ForcedValue = strForceValueChoice1;
                if (!ImprovementManager.CreateImprovements(_objCharacter, Improvement.ImprovementSource.MentorSpirit, _guiID.ToString("D"), _nodChoice1, false, 1, DisplayNameShort(GlobalOptions.Language)))
                {
                    _guiID = Guid.Empty;
                    return;
                }
                if (string.IsNullOrEmpty(_strExtra))
                {
                    _strExtra = ImprovementManager.SelectedValue;
                }
                ImprovementManager.ForcedValue   = strOldForce;
                ImprovementManager.SelectedValue = strOldSelected;
            }
            else if (string.IsNullOrEmpty(_strExtra) && !string.IsNullOrEmpty(strForceValueChoice1))
            {
                _strExtra = strForceValueChoice1;
            }
            _nodChoice2 = xmlMentor.SelectSingleNode("choices/choice[name = \"" + strForceValueChoice2 + "\"]/bonus");
            if (_nodChoice2 != null)
            {
                string strOldForce    = ImprovementManager.ForcedValue;
                string strOldSelected = ImprovementManager.SelectedValue;
                //ImprovementManager.ForcedValue = strForceValueChoice2;
                if (!ImprovementManager.CreateImprovements(_objCharacter, Improvement.ImprovementSource.MentorSpirit, _guiID.ToString("D"), _nodChoice2, false, 1, DisplayNameShort(GlobalOptions.Language)))
                {
                    _guiID = Guid.Empty;
                    return;
                }
                if (string.IsNullOrEmpty(_strExtra))
                {
                    _strExtra = ImprovementManager.SelectedValue;
                }
                ImprovementManager.ForcedValue   = strOldForce;
                ImprovementManager.SelectedValue = strOldSelected;
            }
            else if (string.IsNullOrEmpty(_strExtra) && !string.IsNullOrEmpty(strForceValueChoice2))
            {
                _strExtra = strForceValueChoice2;
            }

            /*
             * if (string.IsNullOrEmpty(_strNotes))
             * {
             *  _strNotes = CommonFunctions.GetTextFromPDF($"{_strSource} {_strPage}", _strName);
             *  if (string.IsNullOrEmpty(_strNotes))
             *  {
             *      _strNotes = CommonFunctions.GetTextFromPDF($"{Source} {Page(GlobalOptions.Language)}", DisplayName(GlobalOptions.Language));
             *  }
             * }*/
        }
Beispiel #10
0
        /// <summary>
        /// Accept the values on the Form and create the required XML data.
        /// </summary>
        private void AcceptForm()
        {
            // Make sure a value has been selected if necessary.
            if (txtTranslateSelection.Visible && string.IsNullOrEmpty(txtSelect.Text))
            {
                Program.MainForm.ShowMessageBox(LanguageManager.GetString("Message_SelectItem"), LanguageManager.GetString("MessageTitle_SelectItem"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Make sure a value has been provided for the name.
            if (string.IsNullOrEmpty(txtName.Text))
            {
                Program.MainForm.ShowMessageBox(LanguageManager.GetString("Message_ImprovementName"), LanguageManager.GetString("MessageTitle_ImprovementName"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtName.Focus();
                return;
            }

            MemoryStream objStream   = new MemoryStream();
            XmlDocument  objBonusXml = new XmlDocument
            {
                XmlResolver = null
            };

            using (XmlWriter objWriter = XmlWriter.Create(objStream))
            {
                // Build the XML for the Improvement.
                XmlNode objFetchNode = _objDocument.SelectSingleNode("/chummer/improvements/improvement[id = \"" + cboImprovemetType.SelectedValue + "\"]");
                string  strInternal  = objFetchNode?["internal"]?.InnerText;
                if (string.IsNullOrEmpty(strInternal))
                {
                    return;
                }
                objWriter.WriteStartDocument();
                // <bonus>
                objWriter.WriteStartElement("bonus");
                // <whatever element>
                objWriter.WriteStartElement(strInternal);

                string strRating = string.Empty;
                if (chkApplyToRating.Checked)
                {
                    strRating = "<applytorating>True</applytorating>";
                }

                // Retrieve the XML data from the document and replace the values as necessary.
                // ReSharper disable once PossibleNullReferenceException
                string strXml = objFetchNode["xml"].InnerText
                                .Replace("{val}", nudVal.Value.ToString(GlobalOptions.InvariantCultureInfo))
                                .Replace("{min}", nudMin.Value.ToString(GlobalOptions.InvariantCultureInfo))
                                .Replace("{max}", nudMax.Value.ToString(GlobalOptions.InvariantCultureInfo))
                                .Replace("{aug}", nudAug.Value.ToString(GlobalOptions.InvariantCultureInfo))
                                .Replace("{free}", chkFree.Checked.ToString(GlobalOptions.InvariantCultureInfo).ToLowerInvariant())
                                .Replace("{select}", txtSelect.Text)
                                .Replace("{applytorating}", strRating);
                objWriter.WriteRaw(strXml);

                // Write the rest of the document.
                // </whatever element>
                objWriter.WriteEndElement();
                // </bonus>
                objWriter.WriteEndElement();
                objWriter.WriteEndDocument();
                objWriter.Flush();

                objStream.Position = 0;

                // Read it back in as an XmlDocument.
                using (StreamReader objReader = new StreamReader(objStream, Encoding.UTF8, true))
                    using (XmlReader objXmlReader = XmlReader.Create(objReader, new XmlReaderSettings {
                        XmlResolver = null
                    }))
                        objBonusXml.Load(objXmlReader);
            }

            // Pluck out the bonus information.
            XmlNode objNode = objBonusXml.SelectSingleNode("/bonus");

            // Pass it to the Improvement Manager so that it can be added to the character.
            string strGuid = Guid.NewGuid().ToString("D", GlobalOptions.InvariantCultureInfo);

            ImprovementManager.CreateImprovements(_objCharacter, Improvement.ImprovementSource.Custom, strGuid, objNode, 1, txtName.Text);

            // If an Improvement was passed in, remove it from the character.
            string strNotes = string.Empty;
            int    intOrder = 0;

            if (EditImprovementObject != null)
            {
                // Copy the notes over to the new item.
                strNotes = EditImprovementObject.Notes;
                intOrder = EditImprovementObject.SortOrder;
                ImprovementManager.RemoveImprovements(_objCharacter, Improvement.ImprovementSource.Custom, EditImprovementObject.SourceName);
            }

            // Find the newly-created Improvement and attach its custom name.
            Improvement objImprovement = _objCharacter.Improvements.FirstOrDefault(imp => imp.SourceName == strGuid);

            if (objImprovement != null)
            {
                objImprovement.CustomName  = txtName.Text;
                objImprovement.CustomId    = cboImprovemetType.SelectedValue.ToString();
                objImprovement.Custom      = true;
                objImprovement.Notes       = strNotes;
                objImprovement.SortOrder   = intOrder;
                objImprovement.CustomGroup = _strCustomGroup;
                NewImprovement             = objImprovement;
            }
            else
            {
                Utils.BreakIfDebug();
            }

            DialogResult = DialogResult.OK;
        }
Beispiel #11
0
        /// <summary>
        /// Accept the selected item and close the form.
        /// </summary>
        private void AcceptForm()
        {
            string strSelectedId = cboLifestyle.SelectedValue?.ToString();

            if (string.IsNullOrEmpty(strSelectedId))
            {
                return;
            }
            XmlNode objXmlLifestyle = _objXmlDocument.SelectSingleNode("/chummer/lifestyles/lifestyle[id = " + strSelectedId.CleanXPath() + ']');

            if (objXmlLifestyle == null)
            {
                return;
            }

            _objLifestyle.Source        = objXmlLifestyle["source"]?.InnerText;
            _objLifestyle.Page          = objXmlLifestyle["page"]?.InnerText;
            _objLifestyle.Name          = txtLifestyleName.Text;
            _objLifestyle.BaseLifestyle = objXmlLifestyle["name"]?.InnerText;
            _objLifestyle.Cost          = Convert.ToDecimal(objXmlLifestyle["cost"]?.InnerText, GlobalSettings.InvariantCultureInfo);
            _objLifestyle.Roommates     = _objLifestyle.TrustFund ? 0 : nudRoommates.ValueAsInt;
            _objLifestyle.Percentage    = nudPercentage.Value;
            _objLifestyle.StyleType     = StyleType;
            _objLifestyle.Dice          = Convert.ToInt32(objXmlLifestyle["dice"]?.InnerText, GlobalSettings.InvariantCultureInfo);
            _objLifestyle.Multiplier    = Convert.ToDecimal(objXmlLifestyle["multiplier"]?.InnerText, GlobalSettings.InvariantCultureInfo);
            _objLifestyle.PrimaryTenant = chkPrimaryTenant.Checked;
            _objLifestyle.TrustFund     = chkTrustFund.Checked;
            _objLifestyle.City          = cboCity.Text;
            _objLifestyle.District      = cboDistrict.Text;
            _objLifestyle.Borough       = cboBorough.Text;

            if (objXmlLifestyle.TryGetField("id", Guid.TryParse, out Guid source))
            {
                _objLifestyle.SourceID = source;
            }
            else
            {
                Log.Warn(new object[] { "Missing id field for xmlnode", objXmlLifestyle });
                Utils.BreakIfDebug();
            }

            HashSet <string> setLifestyleQualityIds = new HashSet <string>();

            foreach (TreeNode objNode in treQualities.Nodes)
            {
                if (!objNode.Checked)
                {
                    continue;
                }
                string strLoopId = objNode.Tag.ToString();
                setLifestyleQualityIds.Add(strLoopId);
                if (_objLifestyle.LifestyleQualities.Any(x => x.SourceIDString == strLoopId))
                {
                    continue;
                }
                XmlNode          objXmlLifestyleQuality = _objXmlDocument.SelectSingleNode("/chummer/qualities/quality[id = " + strLoopId.CleanXPath() + ']');
                LifestyleQuality objQuality             = new LifestyleQuality(_objCharacter);
                objQuality.Create(objXmlLifestyleQuality, _objLifestyle, _objCharacter, QualitySource.Selected);
                _objLifestyle.LifestyleQualities.Add(objQuality);
            }

            foreach (LifestyleQuality objLifestyleQuality in _objLifestyle.LifestyleQualities.Where(x =>
                                                                                                    !setLifestyleQualityIds.Contains(x.SourceIDString)).ToList())
            {
                objLifestyleQuality.Remove(false);
            }

            DialogResult = DialogResult.OK;
        }
        /// <summary>
        /// Generates a character cache, which prevents us from repeatedly loading XmlNodes or caching a full character.
        /// </summary>
        /// <param name="strFile"></param>
        private TreeNode CacheCharacters(string strFile)
        {
            if (!File.Exists(strFile))
            {
                Program.MainForm.ShowMessageBox(this, LanguageManager.GetString("Message_File_Cannot_Be_Accessed") + Environment.NewLine + Environment.NewLine + strFile);
                return(null);
            }

            List <XPathNavigator> lstCharacterXmlStatblocks = new List <XPathNavigator>(3);

            try
            {
                using (ZipArchive zipArchive = ZipFile.Open(strFile, ZipArchiveMode.Read, Encoding.GetEncoding(850)))
                {
                    foreach (ZipArchiveEntry entry in zipArchive.Entries)
                    {
                        string strEntryFullName = entry.FullName;
                        if (strEntryFullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) && strEntryFullName.StartsWith("statblocks_xml", StringComparison.Ordinal))
                        {
                            // If we run into any problems loading the character cache, fail out early.
                            try
                            {
                                XPathDocument xmlSourceDoc;
                                using (StreamReader sr = new StreamReader(entry.Open(), true))
                                    using (XmlReader objXmlReader = XmlReader.Create(sr, GlobalOptions.SafeXmlReaderSettings))
                                        xmlSourceDoc = new XPathDocument(objXmlReader);
                                lstCharacterXmlStatblocks.Add(xmlSourceDoc.CreateNavigator());
                            }
                            // If we run into any problems loading the character cache, fail out early.
                            catch (IOException)
                            {
                                Utils.BreakIfDebug();
                            }
                            catch (XmlException)
                            {
                                Utils.BreakIfDebug();
                            }
                        }
                        else if (strEntryFullName.StartsWith("images", StringComparison.Ordinal) && strEntryFullName.Contains('.'))
                        {
                            string strKey = Path.GetFileName(strEntryFullName);
                            using (Bitmap bmpMugshot = new Bitmap(entry.Open(), true))
                            {
                                Bitmap bmpNewMugshot = bmpMugshot.PixelFormat == PixelFormat.Format32bppPArgb
                                    ? bmpMugshot.Clone() as Bitmap // Clone makes sure file handle is closed
                                    : bmpMugshot.ConvertPixelFormat(PixelFormat.Format32bppPArgb);
                                if (_dicImages.ContainsKey(strKey))
                                {
                                    _dicImages[strKey].Dispose();
                                    _dicImages[strKey] = bmpNewMugshot;
                                }
                                else
                                {
                                    _dicImages.Add(strKey, bmpNewMugshot);
                                }
                            }
                        }
                    }
                }
            }
            catch (IOException)
            {
                Program.MainForm.ShowMessageBox(this, LanguageManager.GetString("Message_File_Cannot_Be_Accessed") + Environment.NewLine + Environment.NewLine + strFile);
                return(null);
            }
            catch (NotSupportedException)
            {
                Program.MainForm.ShowMessageBox(this, LanguageManager.GetString("Message_File_Cannot_Be_Accessed") + Environment.NewLine + Environment.NewLine + strFile);
                return(null);
            }
            catch (UnauthorizedAccessException)
            {
                Program.MainForm.ShowMessageBox(this, LanguageManager.GetString("Message_Insufficient_Permissions_Warning"));
                return(null);
            }

            string   strFileText = strFile.CheapReplace(Application.StartupPath, () => "<" + Application.ProductName + ">");
            TreeNode nodRootNode = new TreeNode
            {
                Text        = strFileText,
                ToolTipText = strFileText
            };

            XPathNavigator xmlMetatypesDocument = XmlManager.LoadXPath("metatypes.xml");

            foreach (XPathNavigator xmlCharacterDocument in lstCharacterXmlStatblocks)
            {
                XPathNavigator xmlBaseCharacterNode = xmlCharacterDocument.SelectSingleNode("/document/public/character");
                if (xmlBaseCharacterNode != null)
                {
                    HeroLabCharacterCache objCache = new HeroLabCharacterCache
                    {
                        PlayerName = xmlBaseCharacterNode.SelectSingleNode("@playername")?.Value ?? string.Empty
                    };
                    string strNameString = xmlBaseCharacterNode.SelectSingleNode("@name")?.Value ?? string.Empty;
                    objCache.CharacterId = strNameString;
                    if (!string.IsNullOrEmpty(strNameString))
                    {
                        int intAsIndex = strNameString.IndexOf(" as ", StringComparison.Ordinal);
                        if (intAsIndex != -1)
                        {
                            objCache.CharacterName  = strNameString.Substring(0, intAsIndex);
                            objCache.CharacterAlias = strNameString.Substring(intAsIndex).TrimStart(" as ").Trim('\'');
                        }
                        else
                        {
                            objCache.CharacterName = strNameString;
                        }
                    }

                    string strRaceString = xmlBaseCharacterNode.SelectSingleNode("race/@name")?.Value;
                    if (strRaceString == "Metasapient")
                    {
                        strRaceString = "A.I.";
                    }
                    if (!string.IsNullOrEmpty(strRaceString))
                    {
                        foreach (XPathNavigator xmlMetatype in xmlMetatypesDocument.Select("/chummer/metatypes/metatype"))
                        {
                            string strMetatypeName = xmlMetatype.SelectSingleNode("name")?.Value ?? string.Empty;
                            if (strMetatypeName == strRaceString)
                            {
                                objCache.Metatype    = strMetatypeName;
                                objCache.Metavariant = "None";
                                break;
                            }

                            foreach (XPathNavigator xmlMetavariant in xmlMetatype.Select("metavariants/metavariant"))
                            {
                                string strMetavariantName = xmlMetavariant.SelectSingleNode("name")?.Value ?? string.Empty;
                                if (strMetavariantName == strRaceString)
                                {
                                    objCache.Metatype    = strMetatypeName;
                                    objCache.Metavariant = strMetavariantName;
                                    break;
                                }
                            }
                        }
                    }

                    objCache.Description = xmlBaseCharacterNode.SelectSingleNode("personal/description")?.Value;
                    objCache.Karma       = xmlBaseCharacterNode.SelectSingleNode("karma/@total")?.Value ?? "0";
                    objCache.Essence     = xmlBaseCharacterNode.SelectSingleNode("attributes/attribute[@name = \"Essence\"]/@text")?.Value;
                    objCache.BuildMethod = xmlBaseCharacterNode.SelectSingleNode("creation/bp/@total")?.Value == "25" ?
                                           CharacterBuildMethod.Priority.ToString() :
                                           CharacterBuildMethod.Karma.ToString();

                    objCache.Created = objCache.Karma != "0";
                    if (!objCache.Created)
                    {
                        XPathNodeIterator xmlJournalEntries = xmlBaseCharacterNode.Select("journals/journal");
                        if (xmlJournalEntries?.Count > 1)
                        {
                            objCache.Created = true;
                        }
                        else if (xmlJournalEntries?.Count == 1 && xmlJournalEntries.Current?.SelectSingleNode("@name")?.Value != "Title")
                        {
                            objCache.Created = true;
                        }
                    }
                    string strImageString = xmlBaseCharacterNode.SelectSingleNode("images/image/@filename")?.Value;
                    if (!string.IsNullOrEmpty(strImageString) && _dicImages.TryGetValue(strImageString, out Bitmap objTemp))
                    {
                        objCache.Mugshot = objTemp;
                    }

                    objCache.FilePath = strFile;
                    TreeNode objNode = new TreeNode
                    {
                        Text        = CalculatedName(objCache),
                        ToolTipText = strFile.CheapReplace(Application.StartupPath, () => "<" + Application.ProductName + ">")
                    };
                    nodRootNode.Nodes.Add(objNode);

                    lock (_lstCharacterCacheLock)
                    {
                        _lstCharacterCache.Add(objCache);
                        objNode.Tag = _lstCharacterCache.IndexOf(objCache);
                    }
                }
            }
            nodRootNode.Expand();
            return(nodRootNode);
        }
Beispiel #13
0
        /// <summary>
        /// Create a Mentor Spirit from an XmlNode.
        /// </summary>
        /// <param name="xmlMentor">XmlNode to create the object from.</param>
        /// <param name="eMentorType">Whether this is a Mentor or a Paragon.</param>
        /// <param name="strForceValueChoice1">Name/Text for Choice 1.</param>
        /// <param name="strForceValueChoice2">Name/Text for Choice 2.</param>
        /// <param name="strForceValue">Force a value to be selected for the Mentor Spirit.</param>
        public void Create(XmlNode xmlMentor, Improvement.ImprovementType eMentorType, string strForceValue = "", string strForceValueChoice1 = "", string strForceValueChoice2 = "")
        {
            _eMentorType          = eMentorType;
            _objCachedMyXmlNode   = null;
            _objCachedMyXPathNode = null;
            xmlMentor.TryGetStringFieldQuickly("name", ref _strName);
            xmlMentor.TryGetStringFieldQuickly("source", ref _strSource);
            xmlMentor.TryGetStringFieldQuickly("page", ref _strPage);
            if (!xmlMentor.TryGetMultiLineStringFieldQuickly("altnotes", ref _strNotes))
            {
                xmlMentor.TryGetMultiLineStringFieldQuickly("notes", ref _strNotes);
            }

            if (string.IsNullOrEmpty(_strNotes))
            {
                _strNotes = CommonFunctions.GetBookNotes(xmlMentor, Name, DisplayNameShort(GlobalSettings.Language), Source, Page,
                                                         DisplayPage(GlobalSettings.Language), _objCharacter);
            }

            if (!xmlMentor.TryGetField("id", Guid.TryParse, out _guiSourceID))
            {
                Log.Warn(new object[] { "Missing id field for xmlnode", xmlMentor });
                Utils.BreakIfDebug();
            }

            // Cache the English list of advantages gained through the Mentor Spirit.
            xmlMentor.TryGetMultiLineStringFieldQuickly("advantage", ref _strAdvantage);
            xmlMentor.TryGetMultiLineStringFieldQuickly("disadvantage", ref _strDisadvantage);

            _nodBonus = xmlMentor["bonus"];
            if (_nodBonus != null)
            {
                string strOldForce    = ImprovementManager.ForcedValue;
                string strOldSelected = ImprovementManager.SelectedValue;
                ImprovementManager.ForcedValue = strForceValue;
                if (!ImprovementManager.CreateImprovements(_objCharacter, Improvement.ImprovementSource.MentorSpirit, _guiID.ToString("D", GlobalSettings.InvariantCultureInfo), _nodBonus, 1, DisplayNameShort(GlobalSettings.Language)))
                {
                    _guiID = Guid.Empty;
                    return;
                }
                _strExtra = ImprovementManager.SelectedValue;
                ImprovementManager.ForcedValue   = strOldForce;
                ImprovementManager.SelectedValue = strOldSelected;
            }
            else if (!string.IsNullOrEmpty(strForceValue))
            {
                _strExtra = strForceValue;
            }
            _nodChoice1 = xmlMentor.SelectSingleNode("choices/choice[name = " + strForceValueChoice1.CleanXPath() + "]/bonus");
            if (_nodChoice1 != null)
            {
                string strOldForce    = ImprovementManager.ForcedValue;
                string strOldSelected = ImprovementManager.SelectedValue;
                //ImprovementManager.ForcedValue = strForceValueChoice1;
                if (!ImprovementManager.CreateImprovements(_objCharacter, Improvement.ImprovementSource.MentorSpirit, _guiID.ToString("D", GlobalSettings.InvariantCultureInfo), _nodChoice1, 1, DisplayNameShort(GlobalSettings.Language)))
                {
                    _guiID = Guid.Empty;
                    return;
                }
                if (string.IsNullOrEmpty(_strExtra))
                {
                    _strExtra = ImprovementManager.SelectedValue;
                }
                ImprovementManager.ForcedValue   = strOldForce;
                ImprovementManager.SelectedValue = strOldSelected;
            }
            else if (string.IsNullOrEmpty(_strExtra) && !string.IsNullOrEmpty(strForceValueChoice1))
            {
                _strExtra = strForceValueChoice1;
            }
            _nodChoice2 = xmlMentor.SelectSingleNode("choices/choice[name = " + strForceValueChoice2.CleanXPath() + "]/bonus");
            if (_nodChoice2 != null)
            {
                string strOldForce    = ImprovementManager.ForcedValue;
                string strOldSelected = ImprovementManager.SelectedValue;
                //ImprovementManager.ForcedValue = strForceValueChoice2;
                if (!ImprovementManager.CreateImprovements(_objCharacter, Improvement.ImprovementSource.MentorSpirit, _guiID.ToString("D", GlobalSettings.InvariantCultureInfo), _nodChoice2, 1, DisplayNameShort(GlobalSettings.Language)))
                {
                    _guiID = Guid.Empty;
                    return;
                }
                if (string.IsNullOrEmpty(_strExtra))
                {
                    _strExtra = ImprovementManager.SelectedValue;
                }
                ImprovementManager.ForcedValue   = strOldForce;
                ImprovementManager.SelectedValue = strOldSelected;
            }
            else if (string.IsNullOrEmpty(_strExtra) && !string.IsNullOrEmpty(strForceValueChoice2))
            {
                _strExtra = strForceValueChoice2;
            }

            /*
             * if (string.IsNullOrEmpty(_strNotes))
             * {
             *  _strNotes = CommonFunctions.GetTextFromPdf(_strSource + ' ' + _strPage, _strName);
             *  if (string.IsNullOrEmpty(_strNotes))
             *  {
             *      _strNotes = CommonFunctions.GetTextFromPdf(Source + ' ' + DisplayPage(GlobalSettings.Language), CurrentDisplayName);
             *  }
             * }
             */
        }
Beispiel #14
0
        /// Create a Martial Art from an XmlNode.
        /// <param name="objXmlArtNode">XmlNode to create the object from.</param>
        public void Create(XmlNode objXmlArtNode)
        {
            if (!objXmlArtNode.TryGetField("id", Guid.TryParse, out _guiSourceID))
            {
                Log.Warn(new object[] { "Missing id field for xmlnode", objXmlArtNode });
                Utils.BreakIfDebug();
            }
            if (objXmlArtNode.TryGetStringFieldQuickly("name", ref _strName))
            {
                _objCachedMyXmlNode = null;
            }
            objXmlArtNode.TryGetStringFieldQuickly("source", ref _strSource);
            objXmlArtNode.TryGetStringFieldQuickly("page", ref _strPage);
            objXmlArtNode.TryGetInt32FieldQuickly("cost", ref _intKarmaCost);
            if (!objXmlArtNode.TryGetStringFieldQuickly("altnotes", ref _strNotes))
            {
                objXmlArtNode.TryGetStringFieldQuickly("notes", ref _strNotes);
            }
            _blnIsQuality = objXmlArtNode["isquality"]?.InnerText == bool.TrueString;

            if (objXmlArtNode["bonus"] != null)
            {
                ImprovementManager.CreateImprovements(_objCharacter, Improvement.ImprovementSource.MartialArt, InternalId,
                                                      objXmlArtNode["bonus"], 1, DisplayNameShort(GlobalOptions.Language));
            }
            if (string.IsNullOrEmpty(Notes))
            {
                string strEnglishNameOnPage = Name;
                string strNameOnPage        = string.Empty;
                // make sure we have something and not just an empty tag
                if (objXmlArtNode.TryGetStringFieldQuickly("nameonpage", ref strNameOnPage) &&
                    !string.IsNullOrEmpty(strNameOnPage))
                {
                    strEnglishNameOnPage = strNameOnPage;
                }

                string strQualityNotes = CommonFunctions.GetTextFromPdf(Source + ' ' + Page, strEnglishNameOnPage);

                if (string.IsNullOrEmpty(strQualityNotes) && GlobalOptions.Language != GlobalOptions.DefaultLanguage)
                {
                    string strTranslatedNameOnPage = CurrentDisplayName;

                    // don't check again it is not translated
                    if (strTranslatedNameOnPage != _strName)
                    {
                        // if we found <altnameonpage>, and is not empty and not the same as english we must use that instead
                        if (objXmlArtNode.TryGetStringFieldQuickly("altnameonpage", ref strNameOnPage) &&
                            !string.IsNullOrEmpty(strNameOnPage) && strNameOnPage != strEnglishNameOnPage)
                        {
                            strTranslatedNameOnPage = strNameOnPage;
                        }

                        Notes = CommonFunctions.GetTextFromPdf(Source + ' ' + DisplayPage(GlobalOptions.Language),
                                                               strTranslatedNameOnPage);
                    }
                }
                else
                {
                    Notes = strQualityNotes;
                }
            }
        }
Beispiel #15
0
        /// Create a Critter Power from an XmlNode.
        /// <param name="objXmlPowerNode">XmlNode to create the object from.</param>
        /// <param name="intRating">Selected Rating for the Gear.</param>
        /// <param name="strForcedValue">Value to forcefully select for any ImprovementManager prompts.</param>
        public void Create(XmlNode objXmlPowerNode, int intRating = 0, string strForcedValue = "")
        {
            if (!objXmlPowerNode.TryGetField("id", Guid.TryParse, out _guiSourceID))
            {
                Log.Warning(new object[] { "Missing id field for power xmlnode", objXmlPowerNode });
                Utils.BreakIfDebug();
            }
            if (objXmlPowerNode.TryGetStringFieldQuickly("name", ref _strName))
            {
                _objCachedMyXmlNode = null;
            }
            _intRating = intRating;
            _nodBonus  = objXmlPowerNode["bonus"];
            if (!objXmlPowerNode.TryGetStringFieldQuickly("altnotes", ref _strNotes))
            {
                objXmlPowerNode.TryGetStringFieldQuickly("notes", ref _strNotes);
            }
            // If the piece grants a bonus, pass the information to the Improvement Manager.
            if (_nodBonus != null)
            {
                ImprovementManager.ForcedValue = strForcedValue;
                if (!ImprovementManager.CreateImprovements(_objCharacter, Improvement.ImprovementSource.CritterPower, _guiID.ToString("D"), _nodBonus, true, intRating, DisplayNameShort(GlobalOptions.Language)))
                {
                    _guiID = Guid.Empty;
                    return;
                }
                if (!string.IsNullOrEmpty(ImprovementManager.SelectedValue))
                {
                    _strExtra = ImprovementManager.SelectedValue;
                }
                else if (intRating != 0)
                {
                    _strExtra = intRating.ToString();
                }
            }
            else if (intRating != 0)
            {
                _strExtra = intRating.ToString();
            }
            else
            {
                _strExtra = strForcedValue;
            }
            objXmlPowerNode.TryGetStringFieldQuickly("category", ref _strCategory);
            objXmlPowerNode.TryGetStringFieldQuickly("type", ref _strType);
            objXmlPowerNode.TryGetStringFieldQuickly("action", ref _strAction);
            objXmlPowerNode.TryGetStringFieldQuickly("range", ref _strRange);
            objXmlPowerNode.TryGetStringFieldQuickly("duration", ref _strDuration);
            objXmlPowerNode.TryGetStringFieldQuickly("source", ref _strSource);
            objXmlPowerNode.TryGetStringFieldQuickly("page", ref _strPage);
            objXmlPowerNode.TryGetInt32FieldQuickly("karma", ref _intKarma);

            /*
             * if (string.IsNullOrEmpty(_strNotes))
             * {
             *  _strNotes = CommonFunctions.GetTextFromPDF($"{_strSource} {_strPage}", _strName);
             *  if (string.IsNullOrEmpty(_strNotes))
             *  {
             *      _strNotes = CommonFunctions.GetTextFromPDF($"{Source} {Page(GlobalOptions.Language)}", DisplayName(GlobalOptions.Language));
             *  }
             * }*/
        }
Beispiel #16
0
        /// <summary>
        /// Load the Power from the XmlNode.
        /// </summary>
        /// <param name="objNode">XmlNode to load.</param>
        public void Load(XmlNode objNode)
        {
            if (!objNode.TryGetField("guid", Guid.TryParse, out _guiID))
            {
                _guiID = Guid.NewGuid();
            }
            objNode.TryGetStringFieldQuickly("name", ref _strName);
            if (!objNode.TryGetGuidFieldQuickly("sourceid", ref _guiSourceID))
            {
                XmlNode node = GetNode(GlobalOptions.Language);
                if (!(node.TryGetField("id", Guid.TryParse, out _guiSourceID)))
                {
                    string strPowerName = Name;
                    int    intPos       = strPowerName.IndexOf('(');
                    if (intPos != -1)
                    {
                        strPowerName = strPowerName.Substring(0, intPos - 1);
                    }
                    XmlDocument objXmlDocument = XmlManager.Load("powers.xml");
                    XmlNode     xmlPower       = objXmlDocument.SelectSingleNode("/chummer/powers/power[starts-with(./name,\"" + strPowerName + "\")]");
                    if (xmlPower.TryGetField("id", Guid.TryParse, out _guiSourceID))
                    {
                        _objCachedMyXmlNode = null;
                    }
                }
            }

            Extra = objNode["extra"]?.InnerText ?? string.Empty;
            _strPointsPerLevel = objNode["pointsperlevel"]?.InnerText;
            objNode.TryGetStringFieldQuickly("action", ref _strAction);
            _strAdeptWayDiscount = objNode["adeptway"]?.InnerText;
            if (string.IsNullOrEmpty(_strAdeptWayDiscount))
            {
                string strPowerName = Name;
                int    intPos       = strPowerName.IndexOf('(');
                if (intPos != -1)
                {
                    strPowerName = strPowerName.Substring(0, intPos - 1);
                }
                _strAdeptWayDiscount = XmlManager.Load("powers.xml").SelectSingleNode("/chummer/powers/power[starts-with(./name,\"" + strPowerName + "\")]/adeptway")?.InnerText ?? string.Empty;
            }
            objNode.TryGetInt32FieldQuickly("rating", ref _intRating);
            objNode.TryGetBoolFieldQuickly("levels", ref _blnLevelsEnabled);
            if (!objNode.TryGetInt32FieldQuickly("maxlevel", ref _intMaxLevels))
            {
                objNode.TryGetInt32FieldQuickly("maxlevels", ref _intMaxLevels);
            }
            objNode.TryGetBoolFieldQuickly("discounted", ref _blnDiscountedAdeptWay);
            objNode.TryGetBoolFieldQuickly("discountedgeas", ref _blnDiscountedGeas);
            objNode.TryGetStringFieldQuickly("bonussource", ref _strBonusSource);
            objNode.TryGetDecFieldQuickly("freepoints", ref _decFreePoints);
            objNode.TryGetDecFieldQuickly("extrapointcost", ref _decExtraPointCost);
            objNode.TryGetStringFieldQuickly("source", ref _strSource);
            objNode.TryGetStringFieldQuickly("page", ref _strPage);
            objNode.TryGetStringFieldQuickly("notes", ref _strNotes);
            Bonus = objNode["bonus"];
            if (objNode["adeptway"] != null)
            {
                _nodAdeptWayRequirements = objNode["adeptwayrequires"] ?? GetNode()?["adeptwayrequires"];
            }
            if (Name != "Improved Reflexes" && Name.StartsWith("Improved Reflexes"))
            {
                XmlNode objXmlPower = XmlManager.Load("powers.xml").SelectSingleNode("/chummer/powers/power[starts-with(./name,\"Improved Reflexes\")]");
                if (objXmlPower != null)
                {
                    if (int.TryParse(Name.TrimStartOnce("Improved Reflexes", true).Trim(), out int intTemp))
                    {
                        Create(objXmlPower, intTemp, null, false);
                        objNode.TryGetStringFieldQuickly("notes", ref _strNotes);
                    }
                }
            }
            else
            {
                XmlNodeList nodEnhancements = objNode.SelectNodes("enhancements/enhancement");
                if (nodEnhancements != null)
                {
                    foreach (XmlNode nodEnhancement in nodEnhancements)
                    {
                        Enhancement objEnhancement = new Enhancement(CharacterObject);
                        objEnhancement.Load(nodEnhancement);
                        objEnhancement.Parent = this;
                        Enhancements.Add(objEnhancement);
                    }
                }
            }

            //TODO: Seems that the MysAd Second Attribute house rule gets accidentally enabled sometimes?
            if (Rating > TotalMaximumLevels)
            {
                Utils.BreakIfDebug();
                Rating = TotalMaximumLevels;
            }
            else if (Rating + FreeLevels > TotalMaximumLevels)
            {
                Utils.BreakIfDebug();
                TotalRating = TotalMaximumLevels;
            }
        }
        /// <summary>
        /// Generates a character cache, which prevents us from repeatedly loading XmlNodes or caching a full character.
        /// </summary>
        /// <param name="strFile"></param>
        /// <param name="objParentNode"></param>
        private TreeNode CacheCharacters(string strFile)
        {
            if (!File.Exists(strFile))
            {
                MessageBox.Show(LanguageManager.GetString("Message_File_Cannot_Be_Accessed", GlobalOptions.Language) + "\n\n" + strFile);
                return(null);
            }

            List <XmlDocument> lstCharacterXmlStatblocks = new List <XmlDocument>();

            try
            {
                using (ZipArchive zipArchive = ZipFile.Open(strFile, ZipArchiveMode.Read, Encoding.GetEncoding(850)))
                {
                    foreach (ZipArchiveEntry entry in zipArchive.Entries)
                    {
                        string strEntryFullName = entry.FullName;
                        if (strEntryFullName.EndsWith(".xml") && strEntryFullName.StartsWith("statblocks_xml"))
                        {
                            XmlDocument xmlSourceDoc = new XmlDocument();
                            // If we run into any problems loading the character cache, fail out early.
                            try
                            {
                                using (StreamReader sr = new StreamReader(entry.Open(), true))
                                {
                                    xmlSourceDoc.Load(sr);
                                    lstCharacterXmlStatblocks.Add(xmlSourceDoc);
                                }
                            }
                            // If we run into any problems loading the character cache, fail out early.
                            catch (IOException)
                            {
                                Utils.BreakIfDebug();
                            }
                            catch (XmlException)
                            {
                                Utils.BreakIfDebug();
                            }
                        }
                        else if (strEntryFullName.StartsWith("images") && strEntryFullName.Contains('.'))
                        {
                            string strKey     = Path.GetFileName(strEntryFullName);
                            Bitmap imgMugshot = (new Bitmap(entry.Open(), true)).ConvertPixelFormat(PixelFormat.Format32bppPArgb);
                            if (_dicImages.ContainsKey(strKey))
                            {
                                _dicImages[strKey] = imgMugshot;
                            }
                            else
                            {
                                _dicImages.Add(strKey, imgMugshot);
                            }
                        }
                    }
                }
            }
            catch (IOException)
            {
                MessageBox.Show(LanguageManager.GetString("Message_File_Cannot_Be_Accessed", GlobalOptions.Language) + "\n\n" + strFile);
                return(null);
            }
            catch (NotSupportedException)
            {
                MessageBox.Show(LanguageManager.GetString("Message_File_Cannot_Be_Accessed", GlobalOptions.Language) + "\n\n" + strFile);
                return(null);
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show(LanguageManager.GetString("Message_Insufficient_Permissions_Warning", GlobalOptions.Language));
                return(null);
            }

            string   strFileText = strFile.CheapReplace(Application.StartupPath, () => "<" + Application.ProductName + ">");
            TreeNode nodRootNode = new TreeNode
            {
                Text        = strFileText,
                ToolTipText = strFileText
            };

            XmlDocument xmlMetatypesDocument = XmlManager.Load("metatypes.xml");

            foreach (XmlDocument xmlCharacterDocument in lstCharacterXmlStatblocks)
            {
                XmlNode xmlBaseCharacterNode = xmlCharacterDocument.SelectSingleNode("/document/public/character");
                if (xmlBaseCharacterNode != null)
                {
                    HeroLabCharacterCache objCache = new HeroLabCharacterCache
                    {
                        PlayerName = xmlBaseCharacterNode.Attributes?["playername"]?.InnerText
                    };
                    string strNameString = xmlBaseCharacterNode.Attributes?["name"]?.InnerText ?? string.Empty;
                    objCache.CharacterId = strNameString;
                    if (!string.IsNullOrEmpty(strNameString))
                    {
                        int intAsIndex = strNameString.IndexOf(" as ", StringComparison.Ordinal);
                        if (intAsIndex != -1)
                        {
                            objCache.CharacterName  = strNameString.Substring(0, intAsIndex);
                            objCache.CharacterAlias = strNameString.Substring(intAsIndex).TrimStart(" as ").Trim('\'');
                        }
                        else
                        {
                            objCache.CharacterName = strNameString;
                        }
                    }

                    string strRaceString = xmlBaseCharacterNode.SelectSingleNode("race/@name")?.InnerText;
                    if (strRaceString == "Metasapient")
                    {
                        strRaceString = "A.I.";
                    }
                    if (!string.IsNullOrEmpty(strRaceString))
                    {
                        using (XmlNodeList xmlMetatypeList = xmlMetatypesDocument.SelectNodes("/chummer/metatypes/metatype"))
                        {
                            if (xmlMetatypeList?.Count > 0)
                            {
                                foreach (XmlNode xmlMetatype in xmlMetatypeList)
                                {
                                    string strMetatypeName = xmlMetatype["name"]?.InnerText ?? string.Empty;
                                    if (strMetatypeName == strRaceString)
                                    {
                                        objCache.Metatype    = strMetatypeName;
                                        objCache.Metavariant = "None";
                                        break;
                                    }

                                    using (XmlNodeList xmlMetavariantList = xmlMetatype.SelectNodes("metavariants/metavariant"))
                                    {
                                        if (xmlMetavariantList?.Count > 0)
                                        {
                                            foreach (XmlNode xmlMetavariant in xmlMetavariantList)
                                            {
                                                string strMetavariantName = xmlMetavariant["name"]?.InnerText ?? string.Empty;
                                                if (strMetavariantName == strRaceString)
                                                {
                                                    objCache.Metatype    = strMetatypeName;
                                                    objCache.Metavariant = strMetavariantName;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    objCache.Description = xmlBaseCharacterNode.SelectSingleNode("personal/description")?.InnerText;
                    objCache.Karma       = xmlBaseCharacterNode.SelectSingleNode("karma/@total")?.InnerText ?? "0";
                    objCache.Essence     = xmlBaseCharacterNode.SelectSingleNode("attributes/attribute[@name = \"Essence\"]/@text")?.InnerText;
                    objCache.BuildMethod = xmlBaseCharacterNode.SelectSingleNode("creation/bp/@total")?.InnerText == "25" ?
                                           CharacterBuildMethod.Priority.ToString() :
                                           CharacterBuildMethod.Karma.ToString();

                    objCache.Created = objCache.Karma != "0";
                    if (!objCache.Created)
                    {
                        XmlNodeList xmlJournalEntries = xmlBaseCharacterNode.SelectNodes("journals/journal");
                        if (xmlJournalEntries?.Count > 1)
                        {
                            objCache.Created = true;
                        }
                        else if (xmlJournalEntries?.Count == 1 && xmlJournalEntries[0]?.Attributes?["name"]?.InnerText != "Title")
                        {
                            objCache.Created = true;
                        }
                    }
                    string strImageString = xmlBaseCharacterNode.SelectSingleNode("images/image/@filename")?.InnerText;
                    if (!string.IsNullOrEmpty(strImageString) && _dicImages.TryGetValue(strImageString, out Bitmap objTemp))
                    {
                        objCache.Mugshot = objTemp;
                    }

                    objCache.FilePath = strFile;
                    TreeNode objNode = new TreeNode
                    {
                        Text        = CalculatedName(objCache),
                        ToolTipText = strFile.CheapReplace(Application.StartupPath, () => "<" + Application.ProductName + ">")
                    };
                    nodRootNode.Nodes.Add(objNode);

                    lock (_lstCharacterCacheLock)
                    {
                        _lstCharacterCache.Add(objCache);
                        objNode.Tag = _lstCharacterCache.IndexOf(objCache);
                    }
                }
            }
            nodRootNode.Expand();
            return(nodRootNode);
        }
Beispiel #18
0
        /// Create a Metamagic from an XmlNode.
        /// <param name="objXmlMetamagicNode">XmlNode to create the object from.</param>
        /// <param name="objSource">Source of the Improvement.</param>
        /// <param name="strForcedValue">Value to forcefully select for any ImprovementManager prompts.</param>
        public void Create(XmlNode objXmlMetamagicNode, Improvement.ImprovementSource objSource, string strForcedValue = "")
        {
            if (!objXmlMetamagicNode.TryGetField("id", Guid.TryParse, out _guiSourceID))
            {
                Log.Warn(new object[] { "Missing id field for xmlnode", objXmlMetamagicNode });
                Utils.BreakIfDebug();
            }

            if (objXmlMetamagicNode.TryGetStringFieldQuickly("name", ref _strName))
            {
                _objCachedMyXmlNode   = null;
                _objCachedMyXPathNode = null;
            }

            objXmlMetamagicNode.TryGetStringFieldQuickly("source", ref _strSource);
            objXmlMetamagicNode.TryGetStringFieldQuickly("page", ref _strPage);
            _eImprovementSource = objSource;
            objXmlMetamagicNode.TryGetInt32FieldQuickly("grade", ref _intGrade);
            if (!objXmlMetamagicNode.TryGetMultiLineStringFieldQuickly("altnotes", ref _strNotes))
            {
                objXmlMetamagicNode.TryGetMultiLineStringFieldQuickly("notes", ref _strNotes);
            }

            string sNotesColor = ColorTranslator.ToHtml(ColorManager.HasNotesColor);

            objXmlMetamagicNode.TryGetStringFieldQuickly("notesColor", ref sNotesColor);
            _colNotes = ColorTranslator.FromHtml(sNotesColor);

            if (string.IsNullOrEmpty(Notes))
            {
                Notes = CommonFunctions.GetBookNotes(objXmlMetamagicNode, Name, CurrentDisplayName, Source, Page,
                                                     DisplayPage(GlobalSettings.Language), _objCharacter);
            }

            _nodBonus = objXmlMetamagicNode["bonus"];
            if (_nodBonus != null)
            {
                int intRating = _objCharacter.SubmersionGrade > 0 ? _objCharacter.SubmersionGrade : _objCharacter.InitiateGrade;

                string strOldFocedValue    = ImprovementManager.ForcedValue;
                string strOldSelectedValue = ImprovementManager.SelectedValue;
                ImprovementManager.ForcedValue = strForcedValue;
                if (!ImprovementManager.CreateImprovements(_objCharacter, objSource, _guiID.ToString("D", GlobalSettings.InvariantCultureInfo), _nodBonus, intRating, DisplayNameShort(GlobalSettings.Language)))
                {
                    _guiID = Guid.Empty;
                    ImprovementManager.ForcedValue = strOldFocedValue;
                    return;
                }
                if (!string.IsNullOrEmpty(ImprovementManager.SelectedValue))
                {
                    _strName             += LanguageManager.GetString("String_Space") + '(' + ImprovementManager.SelectedValue + ')';
                    _objCachedMyXmlNode   = null;
                    _objCachedMyXPathNode = null;
                }
                ImprovementManager.ForcedValue   = strOldFocedValue;
                ImprovementManager.SelectedValue = strOldSelectedValue;
            }

            /*
             * if (string.IsNullOrEmpty(_strNotes))
             * {
             *  _strNotes = CommonFunctions.GetTextFromPdf(_strSource + ' ' + _strPage, _strName);
             *  if (string.IsNullOrEmpty(_strNotes))
             *  {
             *      _strNotes = CommonFunctions.GetTextFromPdf(Source + ' ' + DisplayPage(GlobalSettings.Language), CurrentDisplayName);
             *  }
             * }
             */
        }
        private void frmCreateWeaponMount_Load(object sender, EventArgs e)
        {
            _xmlDoc = XmlManager.Load("vehicles.xml");

            // Populate the Armor Category list.
            XmlNodeList nodeList = _xmlDoc.SelectNodes("/chummer/weaponmounts/weaponmount");

            if (nodeList != null)
            {
                foreach (XmlNode node in nodeList)
                {
                    ListItem objItem = new ListItem();
                    objItem.Value = node["id"].InnerText;
                    objItem.Name  = node.Attributes?["translate"]?.InnerText ?? node["name"].InnerText;
                    switch (node["category"].InnerText)
                    {
                    case "Visibility":
                        _lstVisibility.Add(objItem);
                        break;

                    case "Flexibility":
                        _lstFlexibility.Add(objItem);
                        break;

                    case "Control":
                        _lstControl.Add(objItem);
                        break;

                    case "Size":
                        _lstSize.Add(objItem);
                        break;

                    default:
                        Utils.BreakIfDebug();
                        break;
                    }
                }
            }
            cboSize.BeginUpdate();
            cboSize.ValueMember   = "Value";
            cboSize.DisplayMember = "Name";
            cboSize.DataSource    = _lstSize;
            cboSize.EndUpdate();

            cboVisibility.BeginUpdate();
            cboVisibility.ValueMember   = "Value";
            cboVisibility.DisplayMember = "Name";
            cboVisibility.DataSource    = _lstVisibility;
            cboVisibility.EndUpdate();

            cboFlexibility.BeginUpdate();
            cboFlexibility.ValueMember   = "Value";
            cboFlexibility.DisplayMember = "Name";
            cboFlexibility.DataSource    = _lstFlexibility;
            cboFlexibility.EndUpdate();

            cboControl.BeginUpdate();
            cboControl.ValueMember   = "Value";
            cboControl.DisplayMember = "Name";
            cboControl.DataSource    = _lstControl;
            cboControl.EndUpdate();
            _loading = false;
            comboBox_SelectedIndexChanged(null, null);
        }
Beispiel #20
0
        private static void Main()
        {
            // Set DPI Stuff before anything else, even the mutex
            SetProcessDPI(GlobalSettings.DpiScalingMethodSetting);
            if (IsMainThread)
            {
                SetThreadDPI(GlobalSettings.DpiScalingMethodSetting);
            }
            using (GlobalChummerMutex = new Mutex(false, @"Global\" + ChummerGuid, out bool blnIsNewInstance))
            {
                try
                {
                    try
                    {
                        // Chummer instance already exists, so switch to it instead of opening a new instance
                        if (!blnIsNewInstance || !GlobalChummerMutex.WaitOne(TimeSpan.FromSeconds(2), false))
                        {
                            // Try to get the main chummer process by fetching the Chummer process with the earliest start time
                            Process objMainChummerProcess = MyProcess;
                            foreach (Process objLoopProcess in Process.GetProcessesByName(MyProcess.ProcessName))
                            {
                                if (objLoopProcess.StartTime.Ticks < objMainChummerProcess.StartTime.Ticks)
                                {
                                    objMainChummerProcess = objLoopProcess;
                                }
                            }

                            if (objMainChummerProcess != MyProcess)
                            {
                                NativeMethods.SendMessage(objMainChummerProcess.MainWindowHandle,
                                                          NativeMethods.WM_SHOWME, 0, IntPtr.Zero);

                                string strCommandLineArgumentsJoined =
                                    string.Join("<>", Environment.GetCommandLineArgs());
                                NativeMethods.CopyDataStruct objData = new NativeMethods.CopyDataStruct();
                                IntPtr ptrCommandLineArguments       = IntPtr.Zero;
                                try
                                {
                                    // Allocate memory for the data and copy
                                    objData = NativeMethods.CopyDataFromString(CommandLineArgsDataTypeId, strCommandLineArgumentsJoined);
                                    ptrCommandLineArguments = Marshal.AllocCoTaskMem(Marshal.SizeOf(objData));
                                    Marshal.StructureToPtr(objData, ptrCommandLineArguments, false);
                                    // Send the message
                                    NativeMethods.SendMessage(objMainChummerProcess.MainWindowHandle,
                                                              NativeMethods.WM_COPYDATA, 0, ptrCommandLineArguments);
                                }
                                finally
                                {
                                    // Free the allocated memory after the control has been returned
                                    if (ptrCommandLineArguments != IntPtr.Zero)
                                    {
                                        Marshal.FreeCoTaskMem(ptrCommandLineArguments);
                                    }
                                    if (objData.lpData != IntPtr.Zero)
                                    {
                                        Marshal.FreeHGlobal(objData.lpData);
                                    }
                                }
                            }

                            return;
                        }
                    }
                    catch (AbandonedMutexException e)
                    {
                        Log.Info(e);
                    }

                    //for some fun try out this command line parameter: chummer://plugin:SINners:Load:5ff55b9d-7d1c-4067-a2f5-774127346f4e
                    PageViewTelemetry pvt       = null;
                    DateTimeOffset    startTime = DateTimeOffset.UtcNow;
                    // Set default cultures based on the currently set language
                    CultureInfo.DefaultThreadCurrentCulture   = GlobalSettings.CultureInfo;
                    CultureInfo.DefaultThreadCurrentUICulture = GlobalSettings.CultureInfo;
                    string strPostErrorMessage   = string.Empty;
                    string settingsDirectoryPath = Path.Combine(Utils.GetStartupPath, "settings");
                    if (!Directory.Exists(settingsDirectoryPath))
                    {
                        try
                        {
                            Directory.CreateDirectory(settingsDirectoryPath);
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            string strMessage = LanguageManager.GetString("Message_Insufficient_Permissions_Warning",
                                                                          GlobalSettings.Language, false);
                            if (string.IsNullOrEmpty(strMessage))
                            {
                                strMessage = ex.ToString();
                            }
                            strPostErrorMessage = strMessage;
                        }
                        catch (Exception ex)
                        {
                            strPostErrorMessage = ex.ToString();
                        }
                    }

                    IsMono = Type.GetType("Mono.Runtime") != null;
                    // Delete old ProfileOptimization file because we don't want it anymore, instead we restart profiling for each newly generated assembly
                    Utils.SafeDeleteFile(Path.Combine(Utils.GetStartupPath, "chummerprofile"));
                    // We avoid weird issues with ProfileOptimization pointing JIT to the wrong place by checking for and removing all profile optimization files that
                    // were made in an older version (i.e. an older assembly)
                    string strProfileOptimizationName = "chummerprofile_" + Utils.CurrentChummerVersion + ".profile";
                    foreach (string strProfileFile in Directory.GetFiles(Utils.GetStartupPath, "*.profile", SearchOption.TopDirectoryOnly))
                    {
                        if (!string.Equals(strProfileFile, strProfileOptimizationName,
                                           StringComparison.OrdinalIgnoreCase))
                        {
                            Utils.SafeDeleteFile(strProfileFile);
                        }
                    }
                    // Mono, non-Windows native stuff, and Win11 don't always play nice with ProfileOptimization, so it's better to just not bother with it when running under them
                    if (!IsMono && Utils.HumanReadableOSVersion.StartsWith("Windows") && !Utils.HumanReadableOSVersion.StartsWith("Windows 11"))
                    {
                        ProfileOptimization.SetProfileRoot(Utils.GetStartupPath);
                        ProfileOptimization.StartProfile(strProfileOptimizationName);
                    }

                    Stopwatch sw = Stopwatch.StartNew();
                    //If debugging and launched from other place (Bootstrap), launch debugger
                    if (Environment.GetCommandLineArgs().Contains("/debug") && !Debugger.IsAttached)
                    {
                        Debugger.Launch();
                    }

                    sw.TaskEnd("dbgchk");
                    //Various init stuff (that mostly "can" be removed as they serve
                    //debugging more than function

                    //Needs to be called before Log is setup, as it moves where log might be.
                    FixCwd();

                    sw.TaskEnd("fixcwd");

                    AppDomain.CurrentDomain.FirstChanceException += ExceptionHeatMap.OnException;

                    sw.TaskEnd("appdomain 2");

                    string strInfo =
                        string.Format(GlobalSettings.InvariantCultureInfo,
                                      "Application Chummer5a build {0} started at {1} with command line arguments {2}",
                                      Utils.CurrentChummerVersion, DateTime.UtcNow,
                                      Environment.CommandLine);
                    sw.TaskEnd("infogen");

                    sw.TaskEnd("infoprnt");

                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);

                    sw.TaskEnd("languagefreestartup");

                    void HandleCrash(object o, UnhandledExceptionEventArgs exa)
                    {
                        if (exa.ExceptionObject is Exception ex)
                        {
                            try
                            {
                                if (GlobalSettings.UseLoggingApplicationInsights >= UseAILogging.Crashes &&
                                    ChummerTelemetryClient != null &&
                                    !Utils.IsMilestoneVersion)
                                {
                                    ExceptionTelemetry et = new ExceptionTelemetry(ex)
                                    {
                                        SeverityLevel = SeverityLevel.Critical
                                    };
                                    //we have to enable the uploading of THIS message, so it isn't filtered out in the DropUserdataTelemetryProcessos
                                    foreach (DictionaryEntry d in ex.Data)
                                    {
                                        if ((d.Key != null) && (d.Value != null))
                                        {
                                            et.Properties.Add(d.Key.ToString(), d.Value.ToString());
                                        }
                                    }

                                    et.Properties.Add("IsCrash", bool.TrueString);
                                    CustomTelemetryInitializer ti = new CustomTelemetryInitializer();
                                    ti.Initialize(et);

                                    ChummerTelemetryClient.TrackException(et);
                                    ChummerTelemetryClient.Flush();
                                }
                            }
                            catch (Exception ex1)
                            {
                                Log.Error(ex1);
                            }
#if !DEBUG
                            CrashHandler.WebMiniDumpHandler(ex);
#endif
                        }
                    }

                    AppDomain.CurrentDomain.UnhandledException += HandleCrash;

                    sw.TaskEnd("Startup");

                    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);

                    if (!string.IsNullOrEmpty(LanguageManager.ManagerErrorMessage))
                    {
                        // MainForm is null at the moment, so we have to show error box manually
                        MessageBox.Show(LanguageManager.ManagerErrorMessage, Application.ProductName,
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    if (!string.IsNullOrEmpty(GlobalSettings.ErrorMessage))
                    {
                        // MainForm is null at the moment, so we have to show error box manually
                        MessageBox.Show(GlobalSettings.ErrorMessage, Application.ProductName, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                        return;
                    }

                    if (!string.IsNullOrEmpty(strPostErrorMessage))
                    {
                        // MainForm is null at the moment, so we have to show error box manually
                        MessageBox.Show(strPostErrorMessage, Application.ProductName, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                        return;
                    }

                    try
                    {
                        TelemetryConfiguration.Active.InstrumentationKey = "012fd080-80dc-4c10-97df-4f2cf8c805d5";
                        LogManager.ThrowExceptions = true;
                        if (IsMono)
                        {
                            //Mono Crashes because of Application Insights. Set Logging to local, when Mono Runtime is detected
                            GlobalSettings.UseLoggingApplicationInsights = UseAILogging.OnlyLocal;
                        }
                        if (GlobalSettings.UseLoggingApplicationInsights > UseAILogging.OnlyMetric)
                        {
                            ConfigurationItemFactory.Default.Targets.RegisterDefinition(
                                "ApplicationInsightsTarget",
                                typeof(ApplicationInsightsTarget)
                                );
                        }

                        LogManager.ThrowExceptions = false;
                        Log = LogManager.GetCurrentClassLogger();
                        if (GlobalSettings.UseLogging)
                        {
                            foreach (LoggingRule objRule in LogManager.Configuration.LoggingRules)
                            {
#if DEBUG
                                //enable logging to EventLog when Debugging
                                if (objRule.Levels.Count == 0 && objRule.RuleName == "ELChummer")
                                {
                                    objRule.EnableLoggingForLevels(LogLevel.Trace, LogLevel.Fatal);
                                }
#endif
                                //only change the loglevel, if it's off - otherwise it has been changed manually
                                if (objRule.Levels.Count == 0)
                                {
                                    objRule.EnableLoggingForLevels(LogLevel.Debug, LogLevel.Fatal);
                                }
                            }
                        }

                        if (Settings.Default.UploadClientId == Guid.Empty)
                        {
                            Settings.Default.UploadClientId = Guid.NewGuid();
                            Settings.Default.Save();
                        }

                        if (!Utils.IsUnitTest && GlobalSettings.UseLoggingApplicationInsights >= UseAILogging.OnlyMetric)
                        {
#if DEBUG
                            //If you set true as DeveloperMode (see above), you can see the sending telemetry in the debugging output window in IDE.
                            TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = true;
#else
                            TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = false;
#endif
                            TelemetryConfiguration.Active.TelemetryInitializers.Add(new CustomTelemetryInitializer());
                            TelemetryConfiguration.Active.TelemetryProcessorChainBuilder.Use(next =>
                                                                                             new TranslateExceptionTelemetryProcessor(next));
                            TelemetryConfiguration.Active.TelemetryProcessorChainBuilder.Use(next =>
                                                                                             new DropUserdataTelemetryProcessor(next, Environment.UserName));
                            TelemetryConfiguration.Active.TelemetryProcessorChainBuilder.Build();
                            //for now lets disable live view.We may make another GlobalOption to enable it at a later stage...
                            //var live = new LiveStreamProvider(ApplicationInsightsConfig);
                            //live.Enable();

                            //Log an Event with AssemblyVersion and CultureInfo
                            MetricIdentifier objMetricIdentifier = new MetricIdentifier("Chummer", "Program Start",
                                                                                        "Version", "Culture", "AISetting", "OSVersion");
                            string strOSVersion = Utils.HumanReadableOSVersion;
                            Metric objMetric    = ChummerTelemetryClient.GetMetric(objMetricIdentifier);
                            objMetric.TrackValue(1,
                                                 Utils.CurrentChummerVersion.ToString(),
                                                 CultureInfo.CurrentUICulture.TwoLetterISOLanguageName,
                                                 GlobalSettings.UseLoggingApplicationInsights.ToString(),
                                                 strOSVersion);

                            //Log a page view:
                            pvt = new PageViewTelemetry("frmChummerMain()")
                            {
                                Name = "Chummer Startup: " +
                                       Utils.CurrentChummerVersion,
                                Id        = Settings.Default.UploadClientId.ToString(),
                                Timestamp = startTime
                            };
                            pvt.Context.Operation.Name = "Operation Program.Main()";
                            pvt.Properties.Add("parameters", Environment.CommandLine);

                            UploadObjectAsMetric.UploadObject(ChummerTelemetryClient, typeof(GlobalSettings));
                        }
                        else
                        {
                            TelemetryConfiguration.Active.DisableTelemetry = true;
                        }

                        Log.Info(strInfo);
                        Log.Info("Logging options are set to " + GlobalSettings.UseLogging +
                                 " and Upload-Options are set to "
                                 + GlobalSettings.UseLoggingApplicationInsights + " (Installation-Id: "
                                 + Settings.Default.UploadClientId.ToString("D",
                                                                            GlobalSettings.InvariantCultureInfo) + ").");

                        //make sure the Settings are upgraded/preserved after an upgrade
                        //see for details: https://stackoverflow.com/questions/534261/how-do-you-keep-user-config-settings-across-different-assembly-versions-in-net/534335#534335
                        if (Settings.Default.UpgradeRequired)
                        {
                            if (UnblockPath(AppDomain.CurrentDomain.BaseDirectory))
                            {
                                Settings.Default.Upgrade();
                                Settings.Default.UpgradeRequired = false;
                                Settings.Default.Save();
                            }
                            else
                            {
                                Log.Warn("Files could not be unblocked in " + AppDomain.CurrentDomain.BaseDirectory);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        Log.Error(e);
#if DEBUG
                        throw;
#endif
                    }

                    //load the plugins and maybe work of any command line arguments
                    //arguments come in the form of
                    //              /plugin:Name:Parameter:Argument
                    //              /plugin:SINners:RegisterUriScheme:0
                    bool showMainForm = !Utils.IsUnitTest;
                    bool blnRestoreDefaultLanguage;
                    try
                    {
                        // Make sure the default language has been loaded before attempting to open the Main Form.
                        blnRestoreDefaultLanguage = !LanguageManager.LoadLanguage(GlobalSettings.Language);
                    }
                    // This to catch and handle an extremely strange issue where Chummer tries to load a language it shouldn't and ends up
                    // dereferencing a null value that should be impossible by static code analysis. This code here is a failsafe so that
                    // it at least keeps working in English instead of crashing.
                    catch (NullReferenceException)
                    {
                        Utils.BreakIfDebug();
                        blnRestoreDefaultLanguage = true;
                    }

                    // Restore Chummer's language to en-US if we failed to load the default one.
                    if (blnRestoreDefaultLanguage)
                    {
                        GlobalSettings.Language = GlobalSettings.DefaultLanguage;
                    }
                    MainForm = new ChummerMainForm();
                    try
                    {
                        PluginLoader.LoadPlugins();
                    }
                    catch (ApplicationException)
                    {
                        showMainForm = false;
                    }

                    if (!Utils.IsUnitTest)
                    {
                        string[] strArgs = Environment.GetCommandLineArgs();
                        try
                        {
                            // Process plugin args synchronously because plugin load order can end up mattering
                            foreach (string strArg in strArgs)
                            {
                                if (!strArg.Contains("/plugin"))
                                {
                                    continue;
                                }
                                if (!GlobalSettings.PluginsEnabled)
                                {
                                    const string strMessage =
                                        "Please enable Plugins to use command-line arguments invoking specific plugin-functions!";
                                    Log.Warn(strMessage);
                                    MainForm.ShowMessageBox(strMessage, "Plugins not enabled", MessageBoxButtons.OK,
                                                            MessageBoxIcon.Exclamation);
                                }
                                else
                                {
                                    string strWhatPlugin =
                                        strArg.Substring(strArg.IndexOf("/plugin", StringComparison.Ordinal) + 8);
                                    //some external apps choose to add a '/' before a ':' even in the middle of an url...
                                    strWhatPlugin = strWhatPlugin.TrimStart(':');
                                    int    intEndPlugin = strWhatPlugin.IndexOf(':');
                                    string strParameter = strWhatPlugin.Substring(intEndPlugin + 1);
                                    strWhatPlugin = strWhatPlugin.Substring(0, intEndPlugin);
                                    IPlugin objActivePlugin =
                                        PluginLoader.MyActivePlugins.Find(a => a.ToString() == strWhatPlugin);
                                    if (objActivePlugin == null)
                                    {
                                        if (PluginLoader.MyPlugins.All(a => a.ToString() != strWhatPlugin))
                                        {
                                            string strMessage =
                                                "Plugin " + strWhatPlugin + " is not enabled in the options!" +
                                                Environment.NewLine
                                                + "If you want to use command-line arguments, please enable this plugin and restart the program.";
                                            Log.Warn(strMessage);
                                            MainForm.ShowMessageBox(strMessage, strWhatPlugin + " not enabled",
                                                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                        }
                                    }
                                    else
                                    {
                                        showMainForm &= objActivePlugin.ProcessCommandLine(strParameter);
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            ExceptionTelemetry ex = new ExceptionTelemetry(e)
                            {
                                SeverityLevel = SeverityLevel.Warning
                            };
                            ChummerTelemetryClient?.TrackException(ex);
                            Log.Warn(e);
                        }
                    }

                    // Delete the old executable if it exists (created by the update process).
                    Utils.SafeClearDirectory(Utils.GetStartupPath, "*.old");
                    // Purge the temporary directory
                    Utils.SafeClearDirectory(Utils.GetTempPath());

                    if (showMainForm)
                    {
                        MainForm.MyStartupPvt = pvt;
                        Application.Run(MainForm);
                    }

                    PluginLoader?.Dispose();
                    Log.Info(ExceptionHeatMap.GenerateInfo());
                    if (GlobalSettings.UseLoggingApplicationInsights > UseAILogging.OnlyLocal &&
                        ChummerTelemetryClient != null)
                    {
                        ChummerTelemetryClient.Flush();
                        //we have to wait a bit to give it time to upload the data
                        Console.WriteLine("Waiting a bit to flush logging data...");
                        Utils.SafeSleep(TimeSpan.FromSeconds(2));
                    }
                }
                finally
                {
                    GlobalChummerMutex.ReleaseMutex();
                }
            }
        }
Beispiel #21
0
        /// Create a Critter Power from an XmlNode.
        /// <param name="objXmlPowerNode">XmlNode to create the object from.</param>
        /// <param name="intRating">Selected Rating for the Gear.</param>
        /// <param name="strForcedValue">Value to forcefully select for any ImprovementManager prompts.</param>
        public void Create(XmlNode objXmlPowerNode, int intRating = 0, string strForcedValue = "")
        {
            if (!objXmlPowerNode.TryGetField("id", Guid.TryParse, out _guiSourceID))
            {
                Log.Warn(new object[] { "Missing id field for power xmlnode", objXmlPowerNode });
                Utils.BreakIfDebug();
            }

            if (objXmlPowerNode.TryGetStringFieldQuickly("name", ref _strName))
            {
                _objCachedMyXmlNode   = null;
                _objCachedMyXPathNode = null;
            }

            _intRating = intRating;
            _nodBonus  = objXmlPowerNode.SelectSingleNode("bonus");
            if (!objXmlPowerNode.TryGetMultiLineStringFieldQuickly("altnotes", ref _strNotes))
            {
                objXmlPowerNode.TryGetMultiLineStringFieldQuickly("notes", ref _strNotes);
            }

            string sNotesColor = ColorTranslator.ToHtml(ColorManager.HasNotesColor);

            objXmlPowerNode.TryGetStringFieldQuickly("notesColor", ref sNotesColor);
            _colNotes = ColorTranslator.FromHtml(sNotesColor);

            // If the piece grants a bonus, pass the information to the Improvement Manager.
            if (_nodBonus != null)
            {
                ImprovementManager.ForcedValue = strForcedValue;
                if (!ImprovementManager.CreateImprovements(_objCharacter, Improvement.ImprovementSource.CritterPower, _guiID.ToString("D", GlobalSettings.InvariantCultureInfo), _nodBonus, intRating, DisplayNameShort(GlobalSettings.Language)))
                {
                    _guiID = Guid.Empty;
                    return;
                }
                if (!string.IsNullOrEmpty(ImprovementManager.SelectedValue))
                {
                    _strExtra = ImprovementManager.SelectedValue;
                }
                else if (intRating != 0)
                {
                    _strExtra = intRating.ToString(GlobalSettings.InvariantCultureInfo);
                }
            }
            else if (intRating != 0)
            {
                _strExtra = intRating.ToString(GlobalSettings.InvariantCultureInfo);
            }
            else
            {
                _strExtra = strForcedValue;
            }
            objXmlPowerNode.TryGetStringFieldQuickly("category", ref _strCategory);
            objXmlPowerNode.TryGetStringFieldQuickly("type", ref _strType);
            objXmlPowerNode.TryGetStringFieldQuickly("action", ref _strAction);
            objXmlPowerNode.TryGetStringFieldQuickly("range", ref _strRange);
            objXmlPowerNode.TryGetStringFieldQuickly("duration", ref _strDuration);
            objXmlPowerNode.TryGetStringFieldQuickly("source", ref _strSource);
            objXmlPowerNode.TryGetStringFieldQuickly("page", ref _strPage);
            objXmlPowerNode.TryGetInt32FieldQuickly("karma", ref _intKarma);

            if (string.IsNullOrEmpty(Notes))
            {
                Notes = CommonFunctions.GetBookNotes(objXmlPowerNode, Name, CurrentDisplayName, Source, Page,
                                                     DisplayPage(GlobalSettings.Language), _objCharacter);
            }
        }
Beispiel #22
0
        /// <summary>
        /// Load the selected XML file and its associated custom file.
        /// </summary>
        /// <param name="strFileName">Name of the XML file to load.</param>
        /// <param name="blnLoadFile">Whether to force reloading content even if the file already exists.</param>
        public XmlDocument Load(string strFileName, bool blnLoadFile = false)
        {
            string strPath = Path.Combine(Application.StartupPath, "data", strFileName);

            if (!File.Exists(strPath))
            {
                Utils.BreakIfDebug();
                return(null);
            }
            DateTime datDate = File.GetLastWriteTime(strPath);

            // Look to see if this XmlDocument is already loaded.
            XmlReference objReference = _lstXmlDocuments.Find(x => x.FileName == strFileName);

            if (objReference == null || blnLoadFile)
            {
                // The file was not found in the reference list, so it must be loaded.
                objReference = new XmlReference();
                blnLoadFile  = true;
                _lstXmlDocuments.Add(objReference);
            }
            // The file was found in the List, so check the last write time.
            else if (datDate != objReference.FileDate)
            {
                // The last write time does not match, so it must be reloaded.
                blnLoadFile = true;
            }

            // Create a new document that everything will be merged into.
            XmlDocument objDoc;
            XmlDocument objXmlFile = new XmlDocument();

            if (blnLoadFile)
            {
                objDoc = new XmlDocument();
                // write the root chummer node.
                XmlNode objCont = objDoc.CreateElement("chummer");
                objDoc.AppendChild(objCont);
                // Load the base file and retrieve all of the child nodes.
                objXmlFile.Load(strPath);
                XmlNodeList xmlNodeList = objXmlFile.SelectNodes("/chummer/*");
                if (xmlNodeList != null)
                {
                    foreach (XmlNode objNode in xmlNodeList)
                    {
                        // Append the entire child node to the new document.
                        objDoc.DocumentElement.AppendChild(objDoc.ImportNode(objNode, true));
                    }
                }

                // Load any override data files the user might have. Do not attempt this if we're loading the Improvements file.
                if (strFileName != "improvements.xml")
                {
                    strPath = Path.Combine(Application.StartupPath, "data");
                    foreach (string strFile in Directory.GetFiles(strPath, "override*_" + strFileName))
                    {
                        objXmlFile.Load(strFile);
                        foreach (XmlNode objNode in objXmlFile.SelectNodes("/chummer/*"))
                        {
                            foreach (XmlNode objType in objNode.ChildNodes)
                            {
                                if (objType["id"] != null)
                                {
                                    XmlNode objItem = objDoc.SelectSingleNode("/chummer/" + objNode.Name + "/" + objType.Name + "[id = \"" + objType["id"].InnerText.Replace("&amp;", "&") + "\"]");
                                    if (objItem != null)
                                    {
                                        objItem.InnerXml = objType.InnerXml;
                                    }
                                }
                                else if (objType["name"] != null)
                                {
                                    XmlNode objItem = objDoc.SelectSingleNode("/chummer/" + objNode.Name + "/" + objType.Name + "[name = \"" + objType["name"].InnerText.Replace("&amp;", "&") + "\"]");
                                    if (objItem != null)
                                    {
                                        objItem.InnerXml = objType.InnerXml;
                                    }
                                }
                            }
                        }
                    }

                    // Load any custom data files the user might have. Do not attempt this if we're loading the Improvements file.
                    foreach (string strFile in Directory.GetFiles(strPath, "custom*_" + strFileName))
                    {
                        objXmlFile.Load(strFile);
                        foreach (XmlNode objNode in objXmlFile.SelectNodes("/chummer/*"))
                        {
                            // Look for any items with a duplicate name and pluck them from the node so we don't end up with multiple items with the same name.
                            List <XmlNode> lstDelete = new List <XmlNode>();
                            foreach (XmlNode objChild in objNode.ChildNodes)
                            {
                                if (objChild.ParentNode != null)
                                {
                                    // Only do this if the child has the name or id field since this is what we must match on.
                                    if (objChild["id"] != null && null != objDoc.SelectSingleNode("/chummer/" + objChild.ParentNode.Name + "/" +
                                                                                                  objChild.Name + "[name = \"" +
                                                                                                  objChild["id"].InnerText + "\"]"))
                                    {
                                        lstDelete.Add(objChild);
                                    }
                                    else if (objChild["name"] != null && null != objDoc.SelectSingleNode("/chummer/" + objChild.ParentNode.Name + "/" +
                                                                                                         objChild.Name + "[name = \"" +
                                                                                                         objChild["name"].InnerText + "\"]"))
                                    {
                                        lstDelete.Add(objChild);
                                    }
                                }
                            }
                            // Remove the offending items from the node we're about to merge in.
                            foreach (XmlNode objRemoveNode in lstDelete)
                            {
                                objNode.RemoveChild(objRemoveNode);
                            }

                            // Append the entire child node to the new document.
                            objDoc.DocumentElement?.AppendChild(objDoc.ImportNode(objNode, true));
                        }
                    }
                }

                // Load the translation file for the current base data file if the selected language is not en-us.
                if (GlobalOptions.Instance.Language != "en-us")
                {
                    // Everything is stored in the selected language file to make translations easier, keep all of the language-specific information together, and not require users to download 27 individual files.
                    // The structure is similar to the base data file, but the root node is instead a child /chummer node with a file attribute to indicate the XML file it translates.
                    if (LanguageManager.Instance.DataDoc != null)
                    {
                        foreach (XmlNode objNode in LanguageManager.Instance.DataDoc.SelectNodes("/chummer/chummer[@file = \"" + strFileName + "\"]"))
                        {
                            foreach (XmlNode objType in objNode.ChildNodes)
                            {
                                foreach (XmlNode objChild in objType.ChildNodes)
                                {
                                    if (objChild["name"] != null)
                                    {
                                        // If this is a translatable item, find the proper node and add/update this information.
                                        XmlNode objItem =
                                            objDoc.SelectSingleNode("/chummer/" + objType.Name + "/" + objChild.Name + "[name = \"" +
                                                                    objChild["name"].InnerXml.Replace("&amp;", "&") + "\"]");
                                        if (objItem != null)
                                        {
                                            if (objChild["translate"] != null)
                                            {
                                                objItem.InnerXml += "<translate>" + objChild["translate"].InnerXml + "</translate>";
                                            }
                                            if (objChild["page"] != null)
                                            {
                                                objItem.InnerXml += "<altpage>" + objChild["page"].InnerXml + "</altpage>";
                                            }
                                            if (objChild["code"] != null)
                                            {
                                                objItem.InnerXml += "<altcode>" + objChild["code"].InnerXml + "</altcode>";
                                            }
                                            if (objChild["advantage"] != null)
                                            {
                                                objItem.InnerXml += "<altadvantage>" + objChild["advantage"].InnerXml + "</altadvantage>";
                                            }
                                            if (objChild["disadvantage"] != null)
                                            {
                                                objItem.InnerXml += "<altdisadvantage>" + objChild["disadvantage"].InnerXml + "</altdisadvantage>";
                                            }
                                            if (objChild.Attributes?["translate"] != null)
                                            {
                                                // Handle Category name translations.
                                                (objItem as XmlElement)?.SetAttribute("translate", objChild.Attributes["translate"].InnerXml);
                                            }

                                            // Check for Skill Specialization information.
                                            if (strFileName == "skills.xml")
                                            {
                                                if (objChild["specs"] != null)
                                                {
                                                    foreach (XmlNode objSpec in objChild.SelectNodes("specs/spec"))
                                                    {
                                                        if (objSpec.Attributes?["translate"] != null)
                                                        {
                                                            XmlElement objSpecItem = objItem.SelectSingleNode("specs/spec[. = \"" + objSpec.InnerXml + "\"]") as XmlElement;
                                                            objSpecItem?.SetAttribute("translate", objSpec.Attributes["translate"].InnerXml);
                                                        }
                                                    }
                                                }
                                            }
                                            // Check for Metavariant information.
                                            else if (strFileName == "metatypes.xml")
                                            {
                                                if (objChild["metavariants"] != null)
                                                {
                                                    foreach (XmlNode objMetavariant in objChild.SelectNodes("metavariants/metavariant"))
                                                    {
                                                        if (objMetavariant["name"] != null && objChild["name"] != null)
                                                        {
                                                            XmlNode objMetavariantItem =
                                                                objDoc.SelectSingleNode(
                                                                    "/chummer/metatypes/metatype[name = \"" +
                                                                    objChild["name"].InnerXml +
                                                                    "\"]/metavariants/metavariant[name = \"" +
                                                                    objMetavariant["name"].InnerXml + "\"]");
                                                            if (objMetavariantItem != null)
                                                            {
                                                                if (objMetavariant["translate"] != null)
                                                                {
                                                                    objMetavariantItem.InnerXml += "<translate>" +
                                                                                                   objMetavariant[
                                                                        "translate"].InnerXml +
                                                                                                   "</translate>";
                                                                }
                                                                if (objMetavariant["page"] != null)
                                                                {
                                                                    objMetavariantItem.InnerXml += "<altpage>" +
                                                                                                   objMetavariant["page"]
                                                                                                   .InnerXml +
                                                                                                   "</altpage>";
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            // Check for Martial Art Advantage information.
                                            else if (strFileName == "martialarts.xml")
                                            {
                                                if (objChild["advantages"] != null)
                                                {
                                                    foreach (XmlNode objAdvantage in objChild.SelectNodes("techniques/technique"))
                                                    {
                                                        if (objAdvantage.Attributes?["translate"] != null)
                                                        {
                                                            XmlElement objAdvantageItem = objItem.SelectSingleNode("techniques/technique[. = \"" + objAdvantage.InnerXml + "\"]") as XmlElement;
                                                            objAdvantageItem?.SetAttribute("translate", objAdvantage.Attributes["translate"].InnerXml);
                                                        }
                                                    }
                                                }
                                            }
                                            // Check for Mentor Spirit/Paragon choice information.
                                            else if (strFileName == "mentors.xml" || strFileName == "paragons.xml")
                                            {
                                                if (objChild["choices"] != null)
                                                {
                                                    foreach (XmlNode objChoice in objChild.SelectNodes("choices/choice"))
                                                    {
                                                        if (objChoice["name"] != null && objChoice["translate"] != null)
                                                        {
                                                            XmlNode objChoiceItem = objItem.SelectSingleNode("choices/choice[name = \"" + objChoice["name"].InnerXml + "\"]");
                                                            if (objChoiceItem != null)
                                                            {
                                                                objChoiceItem.InnerXml += "<translate>" + objChoice["translate"].InnerXml + "</translate>";
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    else if (objChild.Attributes?["translate"] != null)
                                    {
                                        // Handle Category name translations.
                                        XmlElement objItem = objDoc.SelectSingleNode("/chummer/" + objType.Name + "/" + objChild.Name + "[. = \"" + objChild.InnerXml.Replace("&amp;", "&") + "\"]") as XmlElement;
                                        // Expected result is null if not found.
                                        objItem?.SetAttribute("translate", objChild.Attributes["translate"].InnerXml);
                                    }
                                }
                            }
                        }
                    }
                }

                // Cache the merged document and its relevant information.
                objReference.FileDate = datDate;
                objReference.FileName = strFileName;
                if (GlobalOptions.Instance.LiveCustomData)
                {
                    objReference.XmlContent = objDoc.Clone() as XmlDocument;
                }
                else
                {
                    objReference.XmlContent = objDoc;
                }
            }
            else
            {
                // A new XmlDocument is created by loading the a copy of the cached one so that we don't stuff custom content into the cached copy
                // (which we don't want and also results in multiple copies of each custom item).
                // Pull the document from cache.
                if (GlobalOptions.Instance.LiveCustomData)
                {
                    objDoc = objReference.XmlContent.Clone() as XmlDocument;
                }
                else
                {
                    objDoc = objReference.XmlContent;
                }
            }

            // Load any custom data files the user might have. Do not attempt this if we're loading the Improvements file.
            if (GlobalOptions.Instance.LiveCustomData && objDoc != null && strFileName != "improvements.xml")
            {
                strPath = Path.Combine(Application.StartupPath, "customdata");
                if (Directory.Exists(strPath))
                {
                    foreach (string strFile in Directory.GetFiles(strPath, "custom*_" + strFileName))
                    {
                        objXmlFile.Load(strFile);
                        foreach (XmlNode objNode in objXmlFile.SelectNodes("/chummer/*"))
                        {
                            // Look for any items with a duplicate name and pluck them from the node so we don't end up with multiple items with the same name.
                            List <XmlNode> lstDelete = new List <XmlNode>();
                            foreach (XmlNode objChild in objNode.ChildNodes)
                            {
                                // Only do this if the child has the name or id field since this is what we must match on.
                                if (objChild["id"] != null &&
                                    null != objDoc.SelectSingleNode("/chummer/" + objChild.ParentNode.Name + "/" +
                                                                    objChild.Name + "[name = \"" +
                                                                    objChild["id"].InnerText + "\"]"))
                                {
                                    lstDelete.Add(objChild);
                                }
                                else if (objChild["name"] != null &&
                                         null != objDoc.SelectSingleNode("/chummer/" + objChild.ParentNode.Name + "/" +
                                                                         objChild.Name + "[name = \"" +
                                                                         objChild["name"].InnerText + "\"]"))
                                {
                                    lstDelete.Add(objChild);
                                }
                            }
                            // Remove the offending items from the node we're about to merge in.
                            foreach (XmlNode objRemoveNode in lstDelete)
                            {
                                objNode.RemoveChild(objRemoveNode);
                            }

                            // Append the entire child node to the new document.
                            objDoc.DocumentElement?.AppendChild(objDoc.ImportNode(objNode, true));
                        }
                    }
                }
            }

            //Check for non-unique guids in the loaded XML file. Ignore improvements.xml since the ids are used in a different way.
            if (strFileName == "improvements.xml" || objReference.DuplicatesChecked)
            {
                return(objDoc);
            }
            {
                foreach (XmlNode objNode in objDoc.SelectNodes("/chummer/*"))
                {
                    //Ignore the version node, if present.
                    if (objNode.Name == "version" || !objNode.HasChildNodes)
                    {
                        continue;
                    }
                    //Parse the node into an XDocument for LINQ parsing.
                    XDocument y       = XDocument.Parse(objNode.OuterXml);
                    string    strNode = (from XmlNode o in objNode.ChildNodes where o.NodeType != XmlNodeType.Comment select o.Name).FirstOrDefault();

                    //Grab the first XML node that isn't a comment.
                    if (strNode == null)
                    {
                        continue;
                    }
                    var duplicatesList = y.Descendants(strNode)
                                         .GroupBy(g => (string)g.Element("id") ?? "")
                                         .Where(g => g.Count() > 1)
                                         .Select(g => g.Key)
                                         .ToList();
                    int i = duplicatesList.Count(o => !string.IsNullOrWhiteSpace(o));
                    if (i <= 0)
                    {
                        objReference.DuplicatesChecked = true;
                        continue;
                    }
                    string duplicates = string.Join("\n", duplicatesList);
                    MessageBox.Show(
                        LanguageManager.Instance.GetString("Message_DuplicateGuidWarning")
                        .Replace("{0}", i.ToString())
                        .Replace("{1}", strFileName)
                        .Replace("{2}", duplicates));
                }
            }

            return(objDoc);
        }
Beispiel #23
0
        public void Dispose()
        {
            if (_blnDisposed)
            {
                return;
            }
            _blnDisposed = true;
            if (_objControl == null)
            {
                lock (s_ObjApplicationWaitCursorsLock)
                {
                    --_intApplicationWaitCursors;
                    if (_intApplicationWaitCursors <= 0)
                    {
                        Application.UseWaitCursor = false;
                    }
                }
                return;
            }
            Log.Trace("CursorWait for Control \"" + _objControl + "\" disposing with Guid \"" + _guidInstance + "\" after " + _objTimer.ElapsedMilliseconds + "ms.");
            _objTimer.Stop();
            if (!s_DicWaitingControls.TryGetValue(_objControl, out ThreadSafeList <CursorWait> lstCursorWaits) || lstCursorWaits == null || lstCursorWaits.Count == 0)
            {
                Utils.BreakIfDebug();
                Log.Error("CursorWait for Control \"" + _objControl + "\" with Guid \"" + _guidInstance + "\" somehow does not have a CursorWait list defined for it");
                throw new InvalidOperationException(nameof(lstCursorWaits));
            }

            int intMyIndex = lstCursorWaits.FindLastIndex(x => x.Equals(this));

            if (intMyIndex < 0 || !lstCursorWaits.Remove(this))
            {
                Utils.BreakIfDebug();
                Log.Error("CursorWait for Control \"" + _objControl + "\" with Guid \"" + _guidInstance + "\" somehow is not in the CursorWait list defined for it");
                throw new InvalidOperationException(nameof(intMyIndex));
            }
            if (intMyIndex >= lstCursorWaits.Count)
            {
                CursorWait objPreviousCursorWait = null;
                // Need this pattern because the size of lstExisting might change in between fetching lstExisting.Count and lstExisting[]
                bool blnDoLoop = true;
                while (blnDoLoop)
                {
                    blnDoLoop = false;
                    int intIndex = lstCursorWaits.Count - 1;
                    if (intIndex >= 0)
                    {
                        try
                        {
                            objPreviousCursorWait = lstCursorWaits[intIndex];
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            blnDoLoop = true;
                        }
                    }
                }
                SetControlCursor(objPreviousCursorWait?.CursorToUse);
            }
            if (lstCursorWaits.Count != 0)
            {
                return;
            }
            s_DicWaitingControls.Remove(_objControl);
            lstCursorWaits.Dispose();
        }
        private void RefreshCBOs()
        {
            XmlNode xmlRequiredNode  = null;
            XmlNode xmlForbiddenNode = null;
            string  strSelectedMount = cboSize.SelectedValue?.ToString();

            if (!string.IsNullOrEmpty(strSelectedMount))
            {
                XmlNode xmlSelectedMount = _xmlDoc.SelectSingleNode("/chummer/weaponmounts/weaponmount[id = \"" + strSelectedMount + "\"]");
                if (xmlSelectedMount != null)
                {
                    xmlForbiddenNode = xmlSelectedMount.SelectSingleNode("forbidden/weaponmountdetails");
                    xmlRequiredNode  = xmlSelectedMount.SelectSingleNode("required/weaponmountdetails");
                }
            }

            XmlNode         xmlVehicleNode = _objVehicle.GetNode();
            List <ListItem> lstVisibility  = new List <ListItem>();
            List <ListItem> lstFlexibility = new List <ListItem>();
            List <ListItem> lstControl     = new List <ListItem>();
            // Populate the Weapon Mount Category list.
            string strFilter = "category != \"Size\" and not(hide)";

            if (!_objVehicle.IsDrone || !GlobalOptions.Dronemods)
            {
                strFilter += " and not(optionaldrone)";
            }
            using (XmlNodeList xmlWeaponMountOptionNodeList = _xmlDoc.SelectNodes("/chummer/weaponmounts/weaponmount[" + strFilter + "]"))
                if (xmlWeaponMountOptionNodeList?.Count > 0)
                {
                    foreach (XmlNode xmlWeaponMountOptionNode in xmlWeaponMountOptionNodeList)
                    {
                        string strId = xmlWeaponMountOptionNode["id"]?.InnerText;
                        if (string.IsNullOrEmpty(strId))
                        {
                            continue;
                        }

                        XmlNode xmlTestNode = xmlWeaponMountOptionNode.SelectSingleNode("forbidden/vehicledetails");
                        if (xmlTestNode != null)
                        {
                            // Assumes topmost parent is an AND node
                            if (xmlVehicleNode.ProcessFilterOperationNode(xmlTestNode, false))
                            {
                                continue;
                            }
                        }
                        xmlTestNode = xmlWeaponMountOptionNode.SelectSingleNode("required/vehicledetails");
                        if (xmlTestNode != null)
                        {
                            // Assumes topmost parent is an AND node
                            if (!xmlVehicleNode.ProcessFilterOperationNode(xmlTestNode, false))
                            {
                                continue;
                            }
                        }

                        string strName    = xmlWeaponMountOptionNode["name"]?.InnerText ?? LanguageManager.GetString("String_Unknown", GlobalOptions.Language);
                        bool   blnAddItem = true;
                        switch (xmlWeaponMountOptionNode["category"]?.InnerText)
                        {
                        case "Visibility":
                        {
                            XmlNodeList xmlNodeList = xmlForbiddenNode?.SelectNodes("visibility");
                            if (xmlNodeList?.Count > 0)
                            {
                                foreach (XmlNode xmlLoopNode in xmlNodeList)
                                {
                                    if (xmlLoopNode.InnerText == strName)
                                    {
                                        blnAddItem = false;
                                        break;
                                    }
                                }
                            }

                            if (xmlRequiredNode != null)
                            {
                                blnAddItem  = false;
                                xmlNodeList = xmlRequiredNode.SelectNodes("visibility");
                                if (xmlNodeList?.Count > 0)
                                {
                                    foreach (XmlNode xmlLoopNode in xmlNodeList)
                                    {
                                        if (xmlLoopNode.InnerText == strName)
                                        {
                                            blnAddItem = true;
                                            break;
                                        }
                                    }
                                }
                            }

                            if (blnAddItem)
                            {
                                lstVisibility.Add(new ListItem(strId, xmlWeaponMountOptionNode["translate"]?.InnerText ?? strName));
                            }
                        }
                        break;

                        case "Flexibility":
                        {
                            XmlNodeList xmlNodeList = xmlForbiddenNode?.SelectNodes("flexibility");
                            if (xmlNodeList?.Count > 0)
                            {
                                foreach (XmlNode xmlLoopNode in xmlNodeList)
                                {
                                    if (xmlLoopNode.InnerText == strName)
                                    {
                                        blnAddItem = false;
                                        break;
                                    }
                                }
                            }

                            if (xmlRequiredNode != null)
                            {
                                blnAddItem  = false;
                                xmlNodeList = xmlRequiredNode.SelectNodes("flexibility");
                                if (xmlNodeList?.Count > 0)
                                {
                                    foreach (XmlNode xmlLoopNode in xmlNodeList)
                                    {
                                        if (xmlLoopNode.InnerText == strName)
                                        {
                                            blnAddItem = true;
                                            break;
                                        }
                                    }
                                }
                            }

                            if (blnAddItem)
                            {
                                lstFlexibility.Add(new ListItem(strId, xmlWeaponMountOptionNode["translate"]?.InnerText ?? strName));
                            }
                        }
                        break;

                        case "Control":
                        {
                            XmlNodeList xmlNodeList = xmlForbiddenNode?.SelectNodes("control");
                            if (xmlNodeList?.Count > 0)
                            {
                                foreach (XmlNode xmlLoopNode in xmlNodeList)
                                {
                                    if (xmlLoopNode.InnerText == strName)
                                    {
                                        blnAddItem = false;
                                        break;
                                    }
                                }
                            }

                            if (xmlRequiredNode != null)
                            {
                                blnAddItem  = false;
                                xmlNodeList = xmlRequiredNode.SelectNodes("control");
                                if (xmlNodeList?.Count > 0)
                                {
                                    foreach (XmlNode xmlLoopNode in xmlNodeList)
                                    {
                                        if (xmlLoopNode.InnerText == strName)
                                        {
                                            blnAddItem = true;
                                            break;
                                        }
                                    }
                                }
                            }

                            if (blnAddItem)
                            {
                                lstControl.Add(new ListItem(strId, xmlWeaponMountOptionNode["translate"]?.InnerText ?? strName));
                            }
                        }
                        break;

                        default:
                            Utils.BreakIfDebug();
                            break;
                        }
                    }
                }

            bool blnOldLoading = _blnLoading;

            _blnLoading = true;
            string strOldVisibility  = cboVisibility.SelectedValue?.ToString();
            string strOldFlexibility = cboFlexibility.SelectedValue?.ToString();
            string strOldControl     = cboControl.SelectedValue?.ToString();

            cboVisibility.BeginUpdate();
            cboVisibility.ValueMember   = "Value";
            cboVisibility.DisplayMember = "Name";
            cboVisibility.DataSource    = lstVisibility;
            cboVisibility.Enabled       = lstVisibility.Count > 1;
            if (!string.IsNullOrEmpty(strOldVisibility))
            {
                cboVisibility.SelectedValue = strOldVisibility;
            }
            if (cboVisibility.SelectedIndex == -1 && lstVisibility.Count > 0)
            {
                cboVisibility.SelectedIndex = 0;
            }
            cboVisibility.EndUpdate();

            cboFlexibility.BeginUpdate();
            cboFlexibility.ValueMember   = "Value";
            cboFlexibility.DisplayMember = "Name";
            cboFlexibility.DataSource    = lstFlexibility;
            cboFlexibility.Enabled       = lstFlexibility.Count > 1;
            if (!string.IsNullOrEmpty(strOldFlexibility))
            {
                cboFlexibility.SelectedValue = strOldFlexibility;
            }
            if (cboFlexibility.SelectedIndex == -1 && lstFlexibility.Count > 0)
            {
                cboFlexibility.SelectedIndex = 0;
            }
            cboFlexibility.EndUpdate();

            cboControl.BeginUpdate();
            cboControl.ValueMember   = "Value";
            cboControl.DisplayMember = "Name";
            cboControl.DataSource    = lstControl;
            cboControl.Enabled       = lstControl.Count > 1;
            if (!string.IsNullOrEmpty(strOldControl))
            {
                cboControl.SelectedValue = strOldControl;
            }
            if (cboControl.SelectedIndex == -1 && lstControl.Count > 0)
            {
                cboControl.SelectedIndex = 0;
            }
            cboControl.EndUpdate();

            _blnLoading = blnOldLoading;
        }
        /// Create a Martial Art Technique from an XmlNode.
        /// <param name="xmlTechniqueDataNode">XmlNode to create the object from.</param>
        public void Create(XmlNode xmlTechniqueDataNode)
        {
            if (!xmlTechniqueDataNode.TryGetField("id", Guid.TryParse, out _guiSourceID))
            {
                Log.Warn(new object[] { "Missing id field for xmlnode", xmlTechniqueDataNode });
                Utils.BreakIfDebug();
            }

            if (xmlTechniqueDataNode.TryGetStringFieldQuickly("name", ref _strName))
            {
                if (!xmlTechniqueDataNode.TryGetStringFieldQuickly("altnotes", ref _strNotes))
                {
                    xmlTechniqueDataNode.TryGetStringFieldQuickly("notes", ref _strNotes);
                }
            }
            xmlTechniqueDataNode.TryGetStringFieldQuickly("source", ref _strSource);
            xmlTechniqueDataNode.TryGetStringFieldQuickly("page", ref _strPage);

            if (string.IsNullOrEmpty(Notes))
            {
                string strEnglishNameOnPage = Name;
                string strNameOnPage        = string.Empty;
                // make sure we have something and not just an empty tag
                if (xmlTechniqueDataNode.TryGetStringFieldQuickly("nameonpage", ref strNameOnPage) &&
                    !string.IsNullOrEmpty(strNameOnPage))
                {
                    strEnglishNameOnPage = strNameOnPage;
                }

                string strQualityNotes = CommonFunctions.GetTextFromPDF(Source + ' ' + Page, strEnglishNameOnPage);

                if (string.IsNullOrEmpty(strQualityNotes) && GlobalOptions.Language != GlobalOptions.DefaultLanguage)
                {
                    string strTranslatedNameOnPage = CurrentDisplayName;

                    // don't check again it is not translated
                    if (strTranslatedNameOnPage != _strName)
                    {
                        // if we found <altnameonpage>, and is not empty and not the same as english we must use that instead
                        if (xmlTechniqueDataNode.TryGetStringFieldQuickly("altnameonpage", ref strNameOnPage) &&
                            !string.IsNullOrEmpty(strNameOnPage) && strNameOnPage != strEnglishNameOnPage)
                        {
                            strTranslatedNameOnPage = strNameOnPage;
                        }

                        Notes = CommonFunctions.GetTextFromPDF(Source + ' ' + DisplayPage(GlobalOptions.Language),
                                                               strTranslatedNameOnPage);
                    }
                }
                else
                {
                    Notes = strQualityNotes;
                }
            }

            if (xmlTechniqueDataNode["bonus"] == null)
            {
                return;
            }
            if (!ImprovementManager.CreateImprovements(_objCharacter, Improvement.ImprovementSource.MartialArtTechnique,
                                                       _guiID.ToString("D", GlobalOptions.InvariantCultureInfo), xmlTechniqueDataNode["bonus"], 1, CurrentDisplayName))
            {
                _guiID = Guid.Empty;
            }
        }
Beispiel #26
0
        public void Dispose()
        {
            if (_blnDisposed)
            {
                return;
            }
            _blnDisposed = true;
            if (_objControl == null)
            {
                lock (_intApplicationWaitCursorsLock)
                {
                    _intApplicationWaitCursors -= 1;
                    if (_intApplicationWaitCursors <= 0)
                    {
                        Application.UseWaitCursor = false;
                    }
                }
                return;
            }
            Log.Trace("CursorWait for Control \"" + _objControl + "\" disposing with Guid \"" + instance.ToString() + "\" after " + objTimer.ElapsedMilliseconds + "ms.");
            objTimer.Stop();
            if (!s_dicWaitingControls.TryGetValue(_objControl, out ConcurrentList <CursorWait> lstCursorWaits) || lstCursorWaits == null || lstCursorWaits.Count <= 0)
            {
                Utils.BreakIfDebug();
                Log.Error("CursorWait for Control \"" + _objControl + "\" with Guid \"" + instance.ToString() + "\" somehow does not have a CursorWait list defined for it");
                throw new ArgumentNullException(nameof(lstCursorWaits));
            }

            int intMyIndex = lstCursorWaits.FindLastIndex(x => x.Equals(this));

            if (intMyIndex < 0 || !lstCursorWaits.Remove(this))
            {
                Utils.BreakIfDebug();
                Log.Error("CursorWait for Control \"" + _objControl + "\" with Guid \"" + instance.ToString() + "\" somehow is not in the CursorWait list defined for it");
                throw new ArgumentNullException(nameof(intMyIndex));
            }
            if (intMyIndex >= lstCursorWaits.Count)
            {
                CursorWait objPreviousCursorWait = null;
                // Need this pattern because the size of lstExisting might change in between fetching lstExisting.Count and lstExisting[]
                do
                {
                    int intIndex = lstCursorWaits.Count - 1;
                    if (intIndex >= 0)
                    {
                        try
                        {
                            objPreviousCursorWait = lstCursorWaits[intIndex];
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            continue;
                        }
                    }
                    break;
                } while (true);
                SetControlCursor(objPreviousCursorWait?.CursorToUse);
            }
            if (lstCursorWaits.Count == 0)
            {
                s_dicWaitingControls.TryRemove(_objControl, out ConcurrentList <CursorWait> _);
            }
        }
Beispiel #27
0
        /// <summary>
        /// Build the list of Metamagics.
        /// </summary>
        private void BuildMetamagicList()
        {
            XmlNodeList     objXmlMetamagicList;
            List <ListItem> lstMetamagics = new List <ListItem>();

            // Load the Metamagic information.
            switch (_objMode)
            {
            case Mode.Metamagic:
                _objXmlDocument = XmlManager.Instance.Load("metamagic.xml");
                break;

            case Mode.Echo:
                _objXmlDocument = XmlManager.Instance.Load("echoes.xml");
                break;
            }

            // If the character has MAG enabled, filter the list based on Adept/Magician availability.
            if (_objCharacter.MAGEnabled)
            {
                if (_objCharacter.MagicianEnabled && !_objCharacter.AdeptEnabled)
                {
                    objXmlMetamagicList = _objXmlDocument.SelectNodes("/chummer/" + _strRoot + "/" + _strNode + "[magician = 'yes' and (" + _objCharacter.Options.BookXPath() + ")]");
                }
                else if (!_objCharacter.MagicianEnabled && _objCharacter.AdeptEnabled)
                {
                    objXmlMetamagicList = _objXmlDocument.SelectNodes("/chummer/" + _strRoot + "/" + _strNode + "[adept = 'yes' and (" + _objCharacter.Options.BookXPath() + ")]");
                }
                else
                {
                    objXmlMetamagicList = _objXmlDocument.SelectNodes("/chummer/" + _strRoot + "/" + _strNode + "[" + _objCharacter.Options.BookXPath() + "]");
                }
            }
            else
            {
                objXmlMetamagicList = _objXmlDocument.SelectNodes("/chummer/" + _strRoot + "/" + _strNode + "[" + _objCharacter.Options.BookXPath() + "]");
            }
            string s = LanguageManager.Instance.GetString(_strNode == "echo" ? "String_Echo" : "String_Metamagic");

            if (objXmlMetamagicList != null)
            {
                foreach (XmlNode objXmlMetamagic in objXmlMetamagicList)
                {
                    bool add = !chkLimitList.Checked ||
                               (chkLimitList.Checked &&
                                Backend.Shared_Methods.SelectionShared.RequirementsMet(objXmlMetamagic, false, _objCharacter,
                                                                                       _objMetatypeDocument, _objCritterDocument, _objQualityDocument, "", s));
                    if (!add)
                    {
                        continue;
                    }
                    ListItem objItem = new ListItem();
                    objItem.Value = objXmlMetamagic["name"]?.InnerText;
                    objItem.Name  = objXmlMetamagic["translate"]?.InnerText ?? objXmlMetamagic["name"]?.InnerText;
                    lstMetamagics.Add(objItem);
                }
            }
            else
            {
                Utils.BreakIfDebug();
            }
            SortListItem objSort = new SortListItem();

            lstMetamagics.Sort(objSort.Compare);
            lstMetamagic.BeginUpdate();
            lstMetamagic.DataSource    = null;
            lstMetamagic.ValueMember   = "Value";
            lstMetamagic.DisplayMember = "Name";
            lstMetamagic.DataSource    = lstMetamagics;
            lstMetamagic.EndUpdate();
        }
Beispiel #28
0
        static void Main()
        {
            //for some fun try out this command line parameter: chummer://plugin:SINners:Load:5ff55b9d-7d1c-4067-a2f5-774127346f4e
            PageViewTelemetry pvt = null;
            var startTime         = DateTimeOffset.UtcNow;

            using (GlobalChummerMutex = new Mutex(false, @"Global\" + strChummerGuid))
            {
                // Set default cultures based on the currently set language
                CultureInfo.DefaultThreadCurrentCulture   = GlobalOptions.CultureInfo;
                CultureInfo.DefaultThreadCurrentUICulture = GlobalOptions.CultureInfo;
                string strPostErrorMessage   = string.Empty;
                string settingsDirectoryPath = Path.Combine(Utils.GetStartupPath, "settings");
                if (!Directory.Exists(settingsDirectoryPath))
                {
                    try
                    {
                        Directory.CreateDirectory(settingsDirectoryPath);
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        string strMessage = LanguageManager.GetString("Message_Insufficient_Permissions_Warning", GlobalOptions.Language, false);
                        if (string.IsNullOrEmpty(strMessage))
                        {
                            strMessage = ex.ToString();
                        }
                        strPostErrorMessage = strMessage;
                    }
                    catch (Exception ex)
                    {
                        strPostErrorMessage = ex.ToString();
                    }
                }
                IsMono = Type.GetType("Mono.Runtime") != null;
                // Mono doesn't always play nice with ProfileOptimization, so it's better to just not bother with it when running under Mono
                if (!IsMono)
                {
                    ProfileOptimization.SetProfileRoot(Utils.GetStartupPath);
                    ProfileOptimization.StartProfile("chummerprofile");
                }

                Stopwatch sw = Stopwatch.StartNew();
                //If debugging and launched from other place (Bootstrap), launch debugger
                if (Environment.GetCommandLineArgs().Contains("/debug") && !Debugger.IsAttached)
                {
                    Debugger.Launch();
                }
                sw.TaskEnd("dbgchk");
                //Various init stuff (that mostly "can" be removed as they serve
                //debugging more than function


                //Needs to be called before Log is setup, as it moves where log might be.
                FixCwd();


                sw.TaskEnd("fixcwd");

                AppDomain.CurrentDomain.FirstChanceException += ExceptionHeatmap.OnException;

                sw.TaskEnd("appdomain 2");

                string strInfo =
                    string.Format(GlobalOptions.InvariantCultureInfo, "Application Chummer5a build {0} started at {1} with command line arguments {2}",
                                  Assembly.GetExecutingAssembly().GetName().Version, DateTime.UtcNow, Environment.CommandLine);
                sw.TaskEnd("infogen");

                sw.TaskEnd("infoprnt");

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                sw.TaskEnd("languagefreestartup");
#if !DEBUG
                AppDomain.CurrentDomain.UnhandledException += (o, e) =>
                {
                    if (e.ExceptionObject is Exception ex)
                    {
                        CrashHandler.WebMiniDumpHandler(ex);
                    }

                    //main.Hide();
                    //main.ShowInTaskbar = false;
                };
#else
                AppDomain.CurrentDomain.UnhandledException += (o, e) =>
                {
                    try
                    {
                        if (e.ExceptionObject is Exception myException)
                        {
                            myException.Data.Add("IsCrash", bool.TrueString);
                            ExceptionTelemetry et = new ExceptionTelemetry(myException)
                            {
                                SeverityLevel = SeverityLevel.Critical
                            };
                            //we have to enable the uploading of THIS message, so it isn't filtered out in the DropUserdataTelemetryProcessos
                            foreach (DictionaryEntry d in myException.Data)
                            {
                                if (d.Key != null && d.Value != null)
                                {
                                    et.Properties.Add(d.Key.ToString(), d.Value.ToString());
                                }
                            }
                            ChummerTelemetryClient.TrackException(myException);
                            ChummerTelemetryClient.Flush();
                        }
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception);
                    }
                };
#endif

                sw.TaskEnd("Startup");

                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);

                if (LanguageManager.ManagerErrorMessage.Length > 0)
                {
                    // MainForm is null at the moment, so we have to show error box manually
                    MessageBox.Show(LanguageManager.ManagerErrorMessage.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (GlobalOptions.ErrorMessage.Length > 0)
                {
                    // MainForm is null at the moment, so we have to show error box manually
                    MessageBox.Show(GlobalOptions.ErrorMessage.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (!string.IsNullOrEmpty(strPostErrorMessage))
                {
                    // MainForm is null at the moment, so we have to show error box manually
                    MessageBox.Show(strPostErrorMessage, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                try
                {
                    TelemetryConfiguration.Active.InstrumentationKey = "012fd080-80dc-4c10-97df-4f2cf8c805d5";
                    LogManager.ThrowExceptions = true;
                    if (GlobalOptions.UseLoggingApplicationInsights > UseAILogging.OnlyMetric)
                    {
                        ConfigurationItemFactory.Default.Targets.RegisterDefinition(
                            "ApplicationInsightsTarget",
                            typeof(ApplicationInsightsTarget)
                            );
                    }

                    LogManager.ThrowExceptions = false;
                    Log = LogManager.GetCurrentClassLogger();
                    if (GlobalOptions.UseLogging)
                    {
                        foreach (var rule in LogManager.Configuration.LoggingRules.ToList())
                        {
                            //only change the loglevel, if it's off - otherwise it has been changed manually
                            if (rule.Levels.Count == 0)
                            {
                                rule.EnableLoggingForLevels(LogLevel.Debug, LogLevel.Fatal);
                            }
                        }
                    }

                    if (Properties.Settings.Default.UploadClientId == Guid.Empty)
                    {
                        Properties.Settings.Default.UploadClientId = Guid.NewGuid();
                        Properties.Settings.Default.Save();
                    }

                    if (GlobalOptions.UseLoggingApplicationInsights >= UseAILogging.OnlyMetric)
                    {
#if DEBUG
                        //If you set true as DeveloperMode (see above), you can see the sending telemetry in the debugging output window in IDE.
                        TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = true;
#else
                        TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = false;
#endif
                        TelemetryConfiguration.Active.TelemetryInitializers.Add(new CustomTelemetryInitializer());
                        TelemetryConfiguration.Active.TelemetryProcessorChainBuilder.Use((next) => new TranslateExceptionTelemetryProcessor(next));
                        var replacePath = Environment.UserName;
                        TelemetryConfiguration.Active.TelemetryProcessorChainBuilder.Use((next) => new DropUserdataTelemetryProcessor(next, replacePath));
                        TelemetryConfiguration.Active.TelemetryProcessorChainBuilder.Build();
                        //for now lets disable live view.We may make another GlobalOption to enable it at a later stage...
                        //var live = new LiveStreamProvider(ApplicationInsightsConfig);
                        //live.Enable();

                        //Log an Event with AssemblyVersion and CultureInfo
                        MetricIdentifier mi        = new MetricIdentifier("Chummer", "Program Start", "Version", "Culture", dimension3Name: "AISetting", dimension4Name: "OSVersion");
                        string           osversion = helpers.Application_Insights.OSVersion.GetOSInfo();
                        var metric = ChummerTelemetryClient.GetMetric(mi);
                        metric.TrackValue(1,
                                          Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                                          CultureInfo.CurrentUICulture.TwoLetterISOLanguageName,
                                          GlobalOptions.UseLoggingApplicationInsights.ToString(),
                                          osversion);

                        //Log a page view:
                        pvt = new PageViewTelemetry("frmChummerMain()")
                        {
                            Name = "Chummer Startup: " +
                                   Assembly.GetExecutingAssembly().GetName().Version,
                            Id = Properties.Settings.Default.UploadClientId.ToString()
                        };
                        pvt.Context.Operation.Name = "Operation Program.Main()";
                        pvt.Properties.Add("parameters", Environment.CommandLine);
                        pvt.Timestamp = startTime;

                        UploadObjectAsMetric.UploadObject(ChummerTelemetryClient, typeof(GlobalOptions));
                    }
                    else
                    {
                        TelemetryConfiguration.Active.DisableTelemetry = true;
                    }
                    if (Utils.IsUnitTest)
                    {
                        TelemetryConfiguration.Active.DisableTelemetry = true;
                    }

                    Log.Info(strInfo);
                    Log.Info(new StringBuilder("Logging options are set to ")
                             .Append(GlobalOptions.UseLogging)
                             .Append(" and Upload-Options are set to ")
                             .Append(GlobalOptions.UseLoggingApplicationInsights)
                             .Append(" (Installation-Id: ")
                             .Append(Properties.Settings.Default.UploadClientId.ToString("D", GlobalOptions.InvariantCultureInfo))
                             .Append(").").ToString());

                    //make sure the Settings are upgraded/preserved after an upgrade
                    //see for details: https://stackoverflow.com/questions/534261/how-do-you-keep-user-config-settings-across-different-assembly-versions-in-net/534335#534335
                    if (Properties.Settings.Default.UpgradeRequired)
                    {
                        if (UnblockPath(AppDomain.CurrentDomain.BaseDirectory))
                        {
                            Properties.Settings.Default.Upgrade();
                            Properties.Settings.Default.UpgradeRequired = false;
                            Properties.Settings.Default.Save();
                        }
                        else
                        {
                            Log.Warn("Files could not be unblocked in " + AppDomain.CurrentDomain.BaseDirectory);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    Log.Error(e);
#if DEBUG
                    throw;
#endif
                }

                //load the plugins and maybe work of any command line arguments
                //arguments come in the form of
                //              /plugin:Name:Parameter:Argument
                //              /plugin:SINners:RegisterUriScheme:0
                bool showMainForm = true;
                // Make sure the default language has been loaded before attempting to open the Main Form.
                LanguageManager.LoadLanguage(GlobalOptions.Language);
                MainForm = new frmChummerMain();
                try
                {
                    PluginLoader.LoadPlugins(null);
                }
                catch (ApplicationException)
                {
                    showMainForm = false;
                }
                if (!Utils.IsUnitTest)
                {
                    string[] strArgs = Environment.GetCommandLineArgs();
                    try
                    {
                        // Hacky, but necessary because innards of Parallel.For would end up invoking
                        // a UI function that would wait for Parallel.For to finish, causing the program
                        // to lock up. Task.Run() delegates Parallel.For to a new thread, preventing this.
                        bool blnIsCompleted = Task.Run(() =>
                        {
                            var loopResult = Parallel.For(1, strArgs.Length, i =>
                            {
                                if (strArgs[i].Contains("/plugin"))
                                {
                                    if (!GlobalOptions.PluginsEnabled)
                                    {
                                        string msg =
                                            "Please enable Plugins to use command-line arguments invoking specific plugin-functions!";
                                        Log.Warn(msg);
                                        MainForm.ShowMessageBox(msg, "Plugins not enabled", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    }
                                    else
                                    {
                                        string whatplugin = strArgs[i].Substring(strArgs[i].IndexOf("/plugin", StringComparison.Ordinal) + 8);
                                        //some external apps choose to add a '/' before a ':' even in the middle of an url...
                                        whatplugin       = whatplugin.TrimStart(':');
                                        int endplugin    = whatplugin.IndexOf(':');
                                        string parameter = whatplugin.Substring(endplugin + 1);
                                        whatplugin       = whatplugin.Substring(0, endplugin);
                                        var plugin       =
                                            PluginLoader.MyActivePlugins.FirstOrDefault(a =>
                                                                                        a.ToString() == whatplugin);
                                        if (plugin == null)
                                        {
                                            if (PluginLoader.MyPlugins.All(a => a.ToString() != whatplugin))
                                            {
                                                string msg = new StringBuilder("Plugin ").Append(whatplugin)
                                                             .AppendLine(" is not enabled in the options!")
                                                             .Append("If you want to use command-line arguments, please enable this plugin and restart the program.").ToString();
                                                Log.Warn(msg);
                                                MainForm.ShowMessageBox(msg, whatplugin + " not enabled", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                            }
                                        }
                                        else
                                        {
                                            showMainForm &= plugin.ProcessCommandLine(parameter);
                                        }
                                    }
                                }
                            });
                            return(loopResult.IsCompleted);
                        }).Result;
                        if (!blnIsCompleted)
                        {
                            Utils.BreakIfDebug();
                        }
                    }
                    catch (Exception e)
                    {
                        ExceptionTelemetry ex = new ExceptionTelemetry(e)
                        {
                            SeverityLevel = SeverityLevel.Warning
                        };
                        ChummerTelemetryClient?.TrackException(ex);
                        Log.Warn(e);
                    }
                }
                if (showMainForm)
                {
                    MainForm.MyStartupPVT = pvt;
                    Application.Run(MainForm);
                }
                PluginLoader?.Dispose();
                Log.Info(ExceptionHeatmap.GenerateInfo());
                if (GlobalOptions.UseLoggingApplicationInsights > UseAILogging.OnlyLocal &&
                    ChummerTelemetryClient != null)
                {
                    ChummerTelemetryClient.Flush();
                    //we have to wait a bit to give it time to upload the data
                    Console.WriteLine("Waiting a bit to flush logging data...");
                    Thread.Sleep(2000);
                }
            }
        }
Beispiel #29
0
        /// <summary>
        /// Generates a character cache, which prevents us from repeatedly loading XmlNodes or caching a full character.
        /// </summary>
        /// <param name="strFile"></param>
        private async Task <TreeNode> CacheCharacters(string strFile)
        {
            if (!File.Exists(strFile))
            {
                Program.ShowMessageBox(
                    this,
                    string.Format(GlobalSettings.CultureInfo,
                                  await LanguageManager.GetStringAsync("Message_File_Cannot_Be_Accessed"), strFile));
                return(null);
            }

            ThreadSafeList <XPathNavigator> lstCharacterXmlStatblocks = new ThreadSafeList <XPathNavigator>(3);

            try
            {
                try
                {
                    using (ZipArchive zipArchive
                               = ZipFile.Open(strFile, ZipArchiveMode.Read, Encoding.GetEncoding(850)))
                    {
                        // NOTE: Cannot parallelize because ZipFile.Open creates one handle on the entire zip file that gets messed up if we try to get it to read multiple files at once
                        foreach (ZipArchiveEntry entry in zipArchive.Entries)
                        {
                            string strEntryFullName = entry.FullName;
                            if (strEntryFullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) &&
                                strEntryFullName.StartsWith("statblocks_xml", StringComparison.Ordinal))
                            {
                                // If we run into any problems loading the character cache, fail out early.
                                try
                                {
                                    using (StreamReader sr = new StreamReader(entry.Open(), true))
                                    {
                                        await Task.Run(() =>
                                        {
                                            XPathDocument xmlSourceDoc;
                                            using (XmlReader objXmlReader
                                                       = XmlReader.Create(sr, GlobalSettings.SafeXmlReaderSettings))
                                                xmlSourceDoc = new XPathDocument(objXmlReader);
                                            XPathNavigator objToAdd = xmlSourceDoc.CreateNavigator();
                                            lstCharacterXmlStatblocks.Add(objToAdd);
                                        });
                                    }
                                }
                                // If we run into any problems loading the character cache, fail out early.
                                catch (IOException)
                                {
                                    Utils.BreakIfDebug();
                                }
                                catch (XmlException)
                                {
                                    Utils.BreakIfDebug();
                                }
                            }
                            else if (strEntryFullName.StartsWith("images", StringComparison.Ordinal) &&
                                     strEntryFullName.Contains('.'))
                            {
                                string strKey = Path.GetFileName(strEntryFullName);
                                using (Bitmap bmpMugshot = new Bitmap(entry.Open(), true))
                                {
                                    Bitmap bmpNewMugshot = bmpMugshot.PixelFormat == PixelFormat.Format32bppPArgb
                                        ? bmpMugshot.Clone() as Bitmap // Clone makes sure file handle is closed
                                        : bmpMugshot.ConvertPixelFormat(PixelFormat.Format32bppPArgb);
                                    while (!await _dicImages.TryAddAsync(strKey, bmpNewMugshot))
                                    {
                                        (bool blnSuccess, Bitmap bmpOldMugshot) =
                                            await _dicImages.TryRemoveAsync(strKey);

                                        if (blnSuccess)
                                        {
                                            bmpOldMugshot?.Dispose();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (IOException)
                {
                    Program.ShowMessageBox(
                        this,
                        string.Format(GlobalSettings.CultureInfo,
                                      await LanguageManager.GetStringAsync("Message_File_Cannot_Be_Accessed"),
                                      strFile));
                    return(null);
                }
                catch (NotSupportedException)
                {
                    Program.ShowMessageBox(
                        this,
                        string.Format(GlobalSettings.CultureInfo,
                                      await LanguageManager.GetStringAsync("Message_File_Cannot_Be_Accessed"),
                                      strFile));
                    return(null);
                }
                catch (UnauthorizedAccessException)
                {
                    Program.ShowMessageBox(
                        this, await LanguageManager.GetStringAsync("Message_Insufficient_Permissions_Warning"));
                    return(null);
                }

                string strFileText
                    = await strFile.CheapReplaceAsync(Utils.GetStartupPath, () => '<' + Application.ProductName + '>');

                TreeNode nodRootNode = new TreeNode
                {
                    Text        = strFileText,
                    ToolTipText = strFileText
                };

                XPathNavigator xmlMetatypesDocument = await XmlManager.LoadXPathAsync("metatypes.xml");

                foreach (XPathNavigator xmlCharacterDocument in lstCharacterXmlStatblocks)
                {
                    XPathNavigator xmlBaseCharacterNode
                        = xmlCharacterDocument.SelectSingleNode("/document/public/character");
                    if (xmlBaseCharacterNode != null)
                    {
                        HeroLabCharacterCache objCache = new HeroLabCharacterCache
                        {
                            PlayerName = xmlBaseCharacterNode.SelectSingleNode("@playername")?.Value ?? string.Empty
                        };
                        string strNameString = xmlBaseCharacterNode.SelectSingleNode("@name")?.Value ?? string.Empty;
                        objCache.CharacterId = strNameString;
                        if (!string.IsNullOrEmpty(strNameString))
                        {
                            int intAsIndex = strNameString.IndexOf(" as ", StringComparison.Ordinal);
                            if (intAsIndex != -1)
                            {
                                objCache.CharacterName = strNameString.Substring(0, intAsIndex);
                                objCache.CharacterAlias
                                    = strNameString.Substring(intAsIndex).TrimStart(" as ").Trim('\'');
                            }
                            else
                            {
                                objCache.CharacterName = strNameString;
                            }
                        }

                        string strRaceString = xmlBaseCharacterNode.SelectSingleNode("race/@name")?.Value;
                        if (strRaceString == "Metasapient")
                        {
                            strRaceString = "A.I.";
                        }
                        if (!string.IsNullOrEmpty(strRaceString))
                        {
                            foreach (XPathNavigator xmlMetatype in xmlMetatypesDocument.Select(
                                         "/chummer/metatypes/metatype"))
                            {
                                string strMetatypeName = xmlMetatype.SelectSingleNode("name")?.Value ?? string.Empty;
                                if (strMetatypeName == strRaceString)
                                {
                                    objCache.Metatype    = strMetatypeName;
                                    objCache.Metavariant = "None";
                                    break;
                                }

                                foreach (XPathNavigator xmlMetavariant in
                                         await xmlMetatype.SelectAndCacheExpressionAsync("metavariants/metavariant"))
                                {
                                    string strMetavariantName
                                        = xmlMetavariant.SelectSingleNode("name")?.Value ?? string.Empty;
                                    if (strMetavariantName == strRaceString)
                                    {
                                        objCache.Metatype    = strMetatypeName;
                                        objCache.Metavariant = strMetavariantName;
                                        break;
                                    }
                                }
                            }
                        }

                        objCache.Description = xmlBaseCharacterNode.SelectSingleNode("personal/description")?.Value;
                        objCache.Karma       = xmlBaseCharacterNode.SelectSingleNode("karma/@total")?.Value ?? "0";
                        objCache.Essence     = xmlBaseCharacterNode
                                               .SelectSingleNode("attributes/attribute[@name = \"Essence\"]/@text")?.Value;
                        objCache.BuildMethod
                            = xmlBaseCharacterNode.SelectSingleNode("creation/bp/@total")?.ValueAsInt <= 100
                                ? CharacterBuildMethod.Priority
                                : CharacterBuildMethod.Karma;

                        string strSettingsSummary =
                            xmlBaseCharacterNode.SelectSingleNode("settings/@summary")?.Value;
                        if (!string.IsNullOrEmpty(strSettingsSummary))
                        {
                            int  intSemicolonIndex;
                            bool blnDoFullHouse = false;
                            int  intSourcebooksIndex
                                = strSettingsSummary.IndexOf("Core Rulebooks:", StringComparison.OrdinalIgnoreCase);
                            if (intSourcebooksIndex != -1)
                            {
                                intSemicolonIndex = strSettingsSummary.IndexOf(';', intSourcebooksIndex);
                                if (intSourcebooksIndex + 16 < intSemicolonIndex)
                                {
                                    blnDoFullHouse
                                        = true; // We probably have multiple books enabled, so use Full House instead
                                }
                            }

                            string strHeroLabSettingsName = "Standard";

                            int intCharCreationSystemsIndex =
                                strSettingsSummary.IndexOf("Character Creation Systems:",
                                                           StringComparison.OrdinalIgnoreCase);
                            if (intCharCreationSystemsIndex != -1)
                            {
                                intSemicolonIndex = strSettingsSummary.IndexOf(';', intCharCreationSystemsIndex);
                                if (intCharCreationSystemsIndex + 28 <= intSemicolonIndex)
                                {
                                    strHeroLabSettingsName = strSettingsSummary.Substring(
                                        intCharCreationSystemsIndex + 28,
                                        strSettingsSummary.IndexOf(
                                            ';', intCharCreationSystemsIndex)
                                        - 28 - intCharCreationSystemsIndex)
                                                             .Trim();
                                    if (strHeroLabSettingsName == "Established Runners")
                                    {
                                        strHeroLabSettingsName = "Standard";
                                    }
                                }
                            }

                            if (strHeroLabSettingsName == "Standard")
                            {
                                if (blnDoFullHouse)
                                {
                                    strHeroLabSettingsName = objCache.BuildMethod == CharacterBuildMethod.Karma
                                        ? "Full House (Point Buy)"
                                        : "Full House";
                                }
                                else if (objCache.BuildMethod == CharacterBuildMethod.Karma)
                                {
                                    strHeroLabSettingsName = "Point Buy";
                                }
                            }

                            objCache.SettingsName = strHeroLabSettingsName;
                        }

                        objCache.Created = objCache.Karma != "0";
                        if (!objCache.Created)
                        {
                            XPathNodeIterator xmlJournalEntries
                                = await xmlBaseCharacterNode.SelectAndCacheExpressionAsync("journals/journal");

                            if (xmlJournalEntries?.Count > 1)
                            {
                                objCache.Created = true;
                            }
                            else if (xmlJournalEntries?.Count == 1 &&
                                     xmlJournalEntries.Current?.SelectSingleNode("@name")?.Value != "Title")
                            {
                                objCache.Created = true;
                            }
                        }

                        string strImageString = xmlBaseCharacterNode.SelectSingleNode("images/image/@filename")?.Value;
                        if (!string.IsNullOrEmpty(strImageString))
                        {
                            (bool blnSuccess, Bitmap objTemp) = await _dicImages.TryGetValueAsync(strImageString);

                            if (blnSuccess)
                            {
                                objCache.Mugshot = objTemp;
                            }
                        }

                        objCache.FilePath = strFile;
                        TreeNode objNode = new TreeNode
                        {
                            Text        = await CalculatedName(objCache),
                            ToolTipText = await strFile.CheapReplaceAsync(Utils.GetStartupPath,
                                                                          () => '<' + Application.ProductName + '>')
                        };
                        nodRootNode.Nodes.Add(objNode);

                        await _lstCharacterCache.AddAsync(objCache);

                        objNode.Tag = await _lstCharacterCache.IndexOfAsync(objCache);
                    }
                }

                nodRootNode.Expand();
                return(nodRootNode);
            }
            finally
            {
                await lstCharacterXmlStatblocks.DisposeAsync();
            }
        }
Beispiel #30
0
        /// <summary>
        /// Returns a 16px x 11px image of a country/region's flag based on its two-letter, ISO-3166 code.
        /// </summary>
        /// <param name="strCode">The ISO-3166 code of the country/region's flag.</param>
        /// <returns>16px x 11px image of the country/region's flag if available, null otherwise</returns>
        public static System.Drawing.Image GetFlagFromCountryCode(string strCode)
        {
            System.Drawing.Image objReturn;
            if (string.IsNullOrEmpty(strCode))
            {
                strCode = "";
            }
            switch (strCode.ToLowerInvariant())
            {
            case "ad":
                objReturn = Properties.Resources.ad;
                break;

            case "ae":
                objReturn = Properties.Resources.ae;
                break;

            case "af":
                objReturn = Properties.Resources.af;
                break;

            case "ag":
                objReturn = Properties.Resources.ag;
                break;

            case "ai":
                objReturn = Properties.Resources.ai;
                break;

            case "al":
                objReturn = Properties.Resources.al;
                break;

            case "am":
                objReturn = Properties.Resources.am;
                break;

            case "an":
                objReturn = Properties.Resources.an;
                break;

            case "ao":
                objReturn = Properties.Resources.ao;
                break;

            case "ar":
                objReturn = Properties.Resources.ar;
                break;

            case "as":
                objReturn = Properties.Resources._as;
                break;

            case "at":
                objReturn = Properties.Resources.at;
                break;

            case "au":
                objReturn = Properties.Resources.au;
                break;

            case "aw":
                objReturn = Properties.Resources.aw;
                break;

            case "ax":
                objReturn = Properties.Resources.ax;
                break;

            case "az":
                objReturn = Properties.Resources.az;
                break;

            case "ba":
                objReturn = Properties.Resources.ba;
                break;

            case "bb":
                objReturn = Properties.Resources.bb;
                break;

            case "bd":
                objReturn = Properties.Resources.bd;
                break;

            case "be":
                objReturn = Properties.Resources.be;
                break;

            case "bf":
                objReturn = Properties.Resources.bf;
                break;

            case "bg":
                objReturn = Properties.Resources.bg;
                break;

            case "bh":
                objReturn = Properties.Resources.bh;
                break;

            case "bi":
                objReturn = Properties.Resources.bi;
                break;

            case "bj":
                objReturn = Properties.Resources.bj;
                break;

            case "bm":
                objReturn = Properties.Resources.bm;
                break;

            case "bn":
                objReturn = Properties.Resources.bn;
                break;

            case "bo":
                objReturn = Properties.Resources.bo;
                break;

            case "br":
                objReturn = Properties.Resources.br;
                break;

            case "bs":
                objReturn = Properties.Resources.bs;
                break;

            case "bt":
                objReturn = Properties.Resources.bt;
                break;

            case "bv":
                objReturn = Properties.Resources.bv;
                break;

            case "bw":
                objReturn = Properties.Resources.bw;
                break;

            case "by":
                objReturn = Properties.Resources.by;
                break;

            case "bz":
                objReturn = Properties.Resources.bz;
                break;

            case "ca":
                objReturn = Properties.Resources.ca;
                break;

            case "cc":
                objReturn = Properties.Resources.cc;
                break;

            case "cd":
                objReturn = Properties.Resources.cd;
                break;

            case "cf":
                objReturn = Properties.Resources.cf;
                break;

            case "cg":
                objReturn = Properties.Resources.cg;
                break;

            case "ch":
                objReturn = Properties.Resources.ch;
                break;

            case "ci":
                objReturn = Properties.Resources.ci;
                break;

            case "ck":
                objReturn = Properties.Resources.ck;
                break;

            case "cl":
                objReturn = Properties.Resources.cl;
                break;

            case "cm":
                objReturn = Properties.Resources.cm;
                break;

            case "cn":
                objReturn = Properties.Resources.cn;
                break;

            case "co":
                objReturn = Properties.Resources.co;
                break;

            case "cr":
                objReturn = Properties.Resources.cr;
                break;

            case "cs":
                objReturn = Properties.Resources.cs;
                break;

            case "ct":
                objReturn = Properties.Resources.ct;
                break;

            case "cu":
                objReturn = Properties.Resources.cu;
                break;

            case "cv":
                objReturn = Properties.Resources.cv;
                break;

            case "cx":
                objReturn = Properties.Resources.cx;
                break;

            case "cy":
                objReturn = Properties.Resources.cy;
                break;

            case "cz":
                objReturn = Properties.Resources.cz;
                break;

            case "de":
                objReturn = Properties.Resources.de;
                break;

            case "dj":
                objReturn = Properties.Resources.dj;
                break;

            case "dk":
                objReturn = Properties.Resources.dk;
                break;

            case "dm":
                objReturn = Properties.Resources.dm;
                break;

            case "do":
                objReturn = Properties.Resources._do;
                break;

            case "dz":
                objReturn = Properties.Resources.dz;
                break;

            case "ec":
                objReturn = Properties.Resources.ec;
                break;

            case "ee":
                objReturn = Properties.Resources.ee;
                break;

            case "eg":
                objReturn = Properties.Resources.eg;
                break;

            case "eh":
                objReturn = Properties.Resources.eh;
                break;

            case "er":
                objReturn = Properties.Resources.er;
                break;

            case "es":
                objReturn = Properties.Resources.es;
                break;

            case "et":
                objReturn = Properties.Resources.et;
                break;

            case "eu":
                objReturn = Properties.Resources.eu;
                break;

            case "fi":
                objReturn = Properties.Resources.fi;
                break;

            case "fj":
                objReturn = Properties.Resources.fj;
                break;

            case "fk":
                objReturn = Properties.Resources.fk;
                break;

            case "fm":
                objReturn = Properties.Resources.fm;
                break;

            case "fo":
                objReturn = Properties.Resources.fo;
                break;

            case "fr":
                objReturn = Properties.Resources.fr;
                break;

            case "ga":
                objReturn = Properties.Resources.ga;
                break;

            case "gb":
                objReturn = Properties.Resources.gb;
                break;

            case "gd":
                objReturn = Properties.Resources.gd;
                break;

            case "ge":
                objReturn = Properties.Resources.ge;
                break;

            case "gf":
                objReturn = Properties.Resources.gf;
                break;

            case "gh":
                objReturn = Properties.Resources.gh;
                break;

            case "gi":
                objReturn = Properties.Resources.gi;
                break;

            case "gl":
                objReturn = Properties.Resources.gl;
                break;

            case "gm":
                objReturn = Properties.Resources.gm;
                break;

            case "gn":
                objReturn = Properties.Resources.gn;
                break;

            case "gp":
                objReturn = Properties.Resources.gp;
                break;

            case "gq":
                objReturn = Properties.Resources.gq;
                break;

            case "gr":
                objReturn = Properties.Resources.gr;
                break;

            case "gs":
                objReturn = Properties.Resources.gs;
                break;

            case "gt":
                objReturn = Properties.Resources.gt;
                break;

            case "gu":
                objReturn = Properties.Resources.gu;
                break;

            case "gw":
                objReturn = Properties.Resources.gw;
                break;

            case "gy":
                objReturn = Properties.Resources.gy;
                break;

            case "hk":
                objReturn = Properties.Resources.hk;
                break;

            case "hm":
                objReturn = Properties.Resources.hm;
                break;

            case "hn":
                objReturn = Properties.Resources.hn;
                break;

            case "hr":
                objReturn = Properties.Resources.hr;
                break;

            case "ht":
                objReturn = Properties.Resources.ht;
                break;

            case "hu":
                objReturn = Properties.Resources.hu;
                break;

            case "id":
                objReturn = Properties.Resources.id;
                break;

            case "ie":
                objReturn = Properties.Resources.ie;
                break;

            case "il":
                objReturn = Properties.Resources.il;
                break;

            case "in":
                objReturn = Properties.Resources._in;
                break;

            case "io":
                objReturn = Properties.Resources.io;
                break;

            case "iq":
                objReturn = Properties.Resources.iq;
                break;

            case "ir":
                objReturn = Properties.Resources.ir;
                break;

            case "is":
                objReturn = Properties.Resources._is;
                break;

            case "it":
                objReturn = Properties.Resources.it;
                break;

            case "jm":
                objReturn = Properties.Resources.jm;
                break;

            case "jo":
                objReturn = Properties.Resources.jo;
                break;

            case "jp":
                objReturn = Properties.Resources.jp;
                break;

            case "ke":
                objReturn = Properties.Resources.ke;
                break;

            case "kg":
                objReturn = Properties.Resources.kg;
                break;

            case "kh":
                objReturn = Properties.Resources.kh;
                break;

            case "ki":
                objReturn = Properties.Resources.ki;
                break;

            case "km":
                objReturn = Properties.Resources.km;
                break;

            case "kn":
                objReturn = Properties.Resources.kn;
                break;

            case "kp":
                objReturn = Properties.Resources.kp;
                break;

            case "kr":
                objReturn = Properties.Resources.kr;
                break;

            case "kw":
                objReturn = Properties.Resources.kw;
                break;

            case "ky":
                objReturn = Properties.Resources.ky;
                break;

            case "kz":
                objReturn = Properties.Resources.kz;
                break;

            case "la":
                objReturn = Properties.Resources.la;
                break;

            case "lb":
                objReturn = Properties.Resources.lb;
                break;

            case "lc":
                objReturn = Properties.Resources.lc;
                break;

            case "li":
                objReturn = Properties.Resources.li;
                break;

            case "lk":
                objReturn = Properties.Resources.lk;
                break;

            case "lr":
                objReturn = Properties.Resources.lr;
                break;

            case "ls":
                objReturn = Properties.Resources.ls;
                break;

            case "lt":
                objReturn = Properties.Resources.lt;
                break;

            case "lu":
                objReturn = Properties.Resources.lu;
                break;

            case "lv":
                objReturn = Properties.Resources.lv;
                break;

            case "ly":
                objReturn = Properties.Resources.ly;
                break;

            case "ma":
                objReturn = Properties.Resources.ma;
                break;

            case "mc":
                objReturn = Properties.Resources.mc;
                break;

            case "md":
                objReturn = Properties.Resources.md;
                break;

            case "me":
                objReturn = Properties.Resources.me;
                break;

            case "mg":
                objReturn = Properties.Resources.mg;
                break;

            case "mh":
                objReturn = Properties.Resources.mh;
                break;

            case "mk":
                objReturn = Properties.Resources.mk;
                break;

            case "ml":
                objReturn = Properties.Resources.ml;
                break;

            case "mm":
                objReturn = Properties.Resources.mm;
                break;

            case "mn":
                objReturn = Properties.Resources.mn;
                break;

            case "mo":
                objReturn = Properties.Resources.mo;
                break;

            case "mp":
                objReturn = Properties.Resources.mp;
                break;

            case "mq":
                objReturn = Properties.Resources.mq;
                break;

            case "mr":
                objReturn = Properties.Resources.mr;
                break;

            case "ms":
                objReturn = Properties.Resources.ms;
                break;

            case "mt":
                objReturn = Properties.Resources.mt;
                break;

            case "mu":
                objReturn = Properties.Resources.mu;
                break;

            case "mv":
                objReturn = Properties.Resources.mv;
                break;

            case "mw":
                objReturn = Properties.Resources.mw;
                break;

            case "mx":
                objReturn = Properties.Resources.mx;
                break;

            case "my":
                objReturn = Properties.Resources.my;
                break;

            case "mz":
                objReturn = Properties.Resources.mz;
                break;

            case "na":
                objReturn = Properties.Resources.na;
                break;

            case "nc":
                objReturn = Properties.Resources.nc;
                break;

            case "ne":
                objReturn = Properties.Resources.ne;
                break;

            case "nf":
                objReturn = Properties.Resources.nf;
                break;

            case "ng":
                objReturn = Properties.Resources.ng;
                break;

            case "ni":
                objReturn = Properties.Resources.ni;
                break;

            case "nl":
                objReturn = Properties.Resources.nl;
                break;

            case "no":
                objReturn = Properties.Resources.no;
                break;

            case "np":
                objReturn = Properties.Resources.np;
                break;

            case "nr":
                objReturn = Properties.Resources.nr;
                break;

            case "nu":
                objReturn = Properties.Resources.nu;
                break;

            case "nz":
                objReturn = Properties.Resources.nz;
                break;

            case "om":
                objReturn = Properties.Resources.om;
                break;

            case "pa":
                objReturn = Properties.Resources.pa;
                break;

            case "pe":
                objReturn = Properties.Resources.pe;
                break;

            case "pf":
                objReturn = Properties.Resources.pf;
                break;

            case "pg":
                objReturn = Properties.Resources.pg;
                break;

            case "ph":
                objReturn = Properties.Resources.ph;
                break;

            case "pk":
                objReturn = Properties.Resources.pk;
                break;

            case "pl":
                objReturn = Properties.Resources.pl;
                break;

            case "pm":
                objReturn = Properties.Resources.pm;
                break;

            case "pn":
                objReturn = Properties.Resources.pn;
                break;

            case "pr":
                objReturn = Properties.Resources.pr;
                break;

            case "ps":
                objReturn = Properties.Resources.ps;
                break;

            case "pt":
                objReturn = Properties.Resources.pt;
                break;

            case "pw":
                objReturn = Properties.Resources.pw;
                break;

            case "py":
                objReturn = Properties.Resources.py;
                break;

            case "qa":
                objReturn = Properties.Resources.qa;
                break;

            case "re":
                objReturn = Properties.Resources.re;
                break;

            case "ro":
                objReturn = Properties.Resources.ro;
                break;

            case "rs":
                objReturn = Properties.Resources.rs;
                break;

            case "ru":
                objReturn = Properties.Resources.ru;
                break;

            case "rw":
                objReturn = Properties.Resources.rw;
                break;

            case "sa":
                objReturn = Properties.Resources.sa;
                break;

            case "sb":
                objReturn = Properties.Resources.sb;
                break;

            case "sc":
                objReturn = Properties.Resources.sc;
                break;

            case "sd":
                objReturn = Properties.Resources.sd;
                break;

            case "se":
                objReturn = Properties.Resources.se;
                break;

            case "sg":
                objReturn = Properties.Resources.sg;
                break;

            case "sh":
                objReturn = Properties.Resources.sh;
                break;

            case "si":
                objReturn = Properties.Resources.si;
                break;

            case "sj":
                objReturn = Properties.Resources.sj;
                break;

            case "sk":
                objReturn = Properties.Resources.sk;
                break;

            case "sl":
                objReturn = Properties.Resources.sl;
                break;

            case "sm":
                objReturn = Properties.Resources.sm;
                break;

            case "sn":
                objReturn = Properties.Resources.sn;
                break;

            case "so":
                objReturn = Properties.Resources.so;
                break;

            case "sr":
                objReturn = Properties.Resources.sr;
                break;

            case "st":
                objReturn = Properties.Resources.st;
                break;

            case "sv":
                objReturn = Properties.Resources.sv;
                break;

            case "sy":
                objReturn = Properties.Resources.sy;
                break;

            case "sz":
                objReturn = Properties.Resources.sz;
                break;

            case "tc":
                objReturn = Properties.Resources.tc;
                break;

            case "td":
                objReturn = Properties.Resources.td;
                break;

            case "tf":
                objReturn = Properties.Resources.tf;
                break;

            case "tg":
                objReturn = Properties.Resources.tg;
                break;

            case "th":
                objReturn = Properties.Resources.th;
                break;

            case "tj":
                objReturn = Properties.Resources.tj;
                break;

            case "tk":
                objReturn = Properties.Resources.tk;
                break;

            case "tl":
                objReturn = Properties.Resources.tl;
                break;

            case "tm":
                objReturn = Properties.Resources.tm;
                break;

            case "tn":
                objReturn = Properties.Resources.tn;
                break;

            case "to":
                objReturn = Properties.Resources.to;
                break;

            case "tr":
                objReturn = Properties.Resources.tr;
                break;

            case "tt":
                objReturn = Properties.Resources.tt;
                break;

            case "tv":
                objReturn = Properties.Resources.tv;
                break;

            case "tw":
                objReturn = Properties.Resources.tw;
                break;

            case "tz":
                objReturn = Properties.Resources.tz;
                break;

            case "ua":
                objReturn = Properties.Resources.ua;
                break;

            case "ug":
                objReturn = Properties.Resources.ug;
                break;

            case "um":
                objReturn = Properties.Resources.um;
                break;

            case "us":
                objReturn = Properties.Resources.us;
                break;

            case "uy":
                objReturn = Properties.Resources.uy;
                break;

            case "uz":
                objReturn = Properties.Resources.uz;
                break;

            case "va":
                objReturn = Properties.Resources.va;
                break;

            case "vc":
                objReturn = Properties.Resources.vc;
                break;

            case "ve":
                objReturn = Properties.Resources.ve;
                break;

            case "vg":
                objReturn = Properties.Resources.vg;
                break;

            case "vi":
                objReturn = Properties.Resources.vi;
                break;

            case "vn":
                objReturn = Properties.Resources.vn;
                break;

            case "vu":
                objReturn = Properties.Resources.vu;
                break;

            case "wf":
                objReturn = Properties.Resources.wf;
                break;

            case "ws":
                objReturn = Properties.Resources.ws;
                break;

            case "xe":
                objReturn = Properties.Resources.xe;
                break;

            case "xs":
                objReturn = Properties.Resources.xs;
                break;

            case "xw":
                objReturn = Properties.Resources.xw;
                break;

            case "ye":
                objReturn = Properties.Resources.ye;
                break;

            case "yt":
                objReturn = Properties.Resources.yt;
                break;

            case "za":
                objReturn = Properties.Resources.za;
                break;

            case "zm":
                objReturn = Properties.Resources.zm;
                break;

            case "zw":
                objReturn = Properties.Resources.zw;
                break;

            case "default":
                objReturn = Properties.Resources.defaulted;
                break;

            case "noimagedots":
                objReturn = Properties.Resources.noimagedots;
                break;

            default:
                Utils.BreakIfDebug();
                objReturn = Properties.Resources.defaulted;
                break;
            }
            return(objReturn);
        }