示例#1
0
        /// <summary>
        /// Decompress multiple files from a single zip file.
        /// </summary>
        /// /// <param name="bytBuffer">Byte array that contains the zip file.</param>
        public void DecompressCharacterSheet(byte[] bytBuffer)
        {
            string strFilePath = Path.Combine(GlobalOptions.ApplicationPath(), "sheets");

            strFilePath = Path.Combine(strFilePath, "omae");
            MemoryStream objStream = new MemoryStream();

            objStream.Write(bytBuffer, 0, bytBuffer.Length);
            Package objPackage = ZipPackage.Open(objStream, FileMode.Open, FileAccess.Read);

            foreach (PackagePart objPart in objPackage.GetParts())
            {
                string strTarget = Path.Combine(strFilePath, objPart.Uri.ToString().Replace("/", string.Empty).Replace('_', ' '));

                Stream objSource      = objPart.GetStream(FileMode.Open, FileAccess.Read);
                Stream objDestination = File.OpenWrite(strTarget);
                byte[] bytFileBuffer  = new byte[100000];
                int    intRead;
                intRead = objSource.Read(bytFileBuffer, 0, bytFileBuffer.Length);
                while (intRead > 0)
                {
                    objDestination.Write(bytFileBuffer, 0, intRead);
                    intRead = objSource.Read(bytFileBuffer, 0, bytFileBuffer.Length);
                }
                objDestination.Close();
                objSource.Close();
            }
        }
示例#2
0
        /// <summary>
        /// Run the generated XML file through the XSL transformation engine to create the file output.
        /// </summary>
        private void GenerateOutput()
        {
            XslCompiledTransform objXSLTransform = new XslCompiledTransform();

            objXSLTransform.Load(GlobalOptions.ApplicationPath() + Path.DirectorySeparatorChar + "sheets" + Path.DirectorySeparatorChar + _strSelectedSheet + ".xsl");

            MemoryStream  objStream = new MemoryStream();
            XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.UTF8);

            objXSLTransform.Transform(_objCharacterXML, null, objWriter);
            objStream.Position = 0;

            // This reads from a static file, outputs to an HTML file, then has the browser read from that file. For debugging purposes.
            //objXSLTransform.Transform("D:\\temp\\print.xml", "D:\\temp\\output.htm");
            //webBrowser1.Navigate("D:\\temp\\output.htm");

            if (!GlobalOptions.Instance.PrintToFileFirst)
            {
                // Populate the browser using the DocumentStream.
                webBrowser1.DocumentStream = objStream;
            }
            else
            {
                // The DocumentStream method fails when using Wine, so we'll instead dump everything out a temporary HTML file, have the WebBrowser load that, then delete the temporary file.
                // Read in the resulting code and pass it to the browser.
                string       strName   = Guid.NewGuid().ToString() + ".htm";
                StreamReader objReader = new StreamReader(objStream);
                string       strOutput = objReader.ReadToEnd();
                File.WriteAllText(strName, strOutput);
                string curDir = Directory.GetCurrentDirectory();
                webBrowser1.Url = new Uri(String.Format("file:///{0}/" + strName, curDir));
                File.Delete(strName);
            }
        }
示例#3
0
        /// <summary>
        /// Decompress multiple files from a single zip file.
        /// </summary>
        /// <param name="bytBuffer">Byte array that contains the zip file.</param>
        /// <param name="strPrefix">Prefix to attach to the decompressed files.</param>
        public void DecompressDataFile(byte[] bytBuffer, string strPrefix)
        {
            string       strFilePath = Path.Combine(GlobalOptions.ApplicationPath(), "data");
            MemoryStream objStream   = new MemoryStream();

            objStream.Write(bytBuffer, 0, bytBuffer.Length);
            Package objPackage = ZipPackage.Open(objStream, FileMode.Open, FileAccess.Read);

            foreach (PackagePart objPart in objPackage.GetParts())
            {
                string strTarget = Path.Combine(strFilePath, objPart.Uri.ToString().Replace("/", string.Empty));
                strTarget = strTarget.Replace("\\override", Path.DirectorySeparatorChar + "override" + strPrefix);
                strTarget = strTarget.Replace("\\custom", Path.DirectorySeparatorChar + "custom" + strPrefix);

                Stream objSource      = objPart.GetStream(FileMode.Open, FileAccess.Read);
                Stream objDestination = File.OpenWrite(strTarget);
                byte[] bytFileBuffer  = new byte[100000];
                int    intRead;
                intRead = objSource.Read(bytFileBuffer, 0, bytFileBuffer.Length);
                while (intRead > 0)
                {
                    objDestination.Write(bytFileBuffer, 0, intRead);
                    intRead = objSource.Read(bytFileBuffer, 0, bytFileBuffer.Length);
                }
                objDestination.Close();
                objSource.Close();
            }
        }
示例#4
0
        /// <summary>
        /// Load the English document and cache it in the List of LanguageStrings so it only needs to be read in once.
        /// </summary>
        private static void RefreshStrings()
        {
            try
            {
                _objDictionary.Clear();
                XmlDocument objEnglishDocument = new XmlDocument();
                string      strFilePath        = Path.Combine(GlobalOptions.ApplicationPath(), "lang");
                strFilePath = Path.Combine(strFilePath, "en-us.xml");
                objEnglishDocument.Load(strFilePath);
                foreach (XmlNode objNode in objEnglishDocument.SelectNodes("/chummer/strings/string"))
                {
                    LanguageString objString = new LanguageString();
                    objString.Key  = objNode["key"].InnerText;
                    objString.Text = objNode["text"].InnerText;
                    _objDictionary.Add(objNode["key"].InnerText, objNode["text"].InnerText);
                }

                if (GlobalOptions.Instance.Language != "en-us")
                {
                    LoadTranslatedString();
                }

                _blnLoaded = true;
            }
            catch
            {
                MessageBox.Show("Could not load default language file!", "Default Language Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
        }
示例#5
0
        private void cmdOK_Click(object sender, EventArgs e)
        {
            if (cboXSLT.Text == string.Empty)
            {
                return;
            }

            // Look for the file extension information.
            string       strLine      = "";
            string       strExtension = "xml";
            StreamReader objFile      = new StreamReader(GlobalOptions.ApplicationPath() + Path.DirectorySeparatorChar + "export" + Path.DirectorySeparatorChar + cboXSLT.Text + ".xsl");

            while ((strLine = objFile.ReadLine()) != null)
            {
                if (strLine.StartsWith("<!-- ext:"))
                {
                    strExtension = strLine.Replace("<!-- ext:", string.Empty).Replace("-->", string.Empty).Trim();
                }
            }
            objFile.Close();

            string strSaveFile = "";

            SaveFileDialog1.Filter = strExtension.ToUpper() + "|*." + strExtension;
            SaveFileDialog1.Title  = LanguageManager.Instance.GetString("Button_Viewer_SaveAsHtml");
            SaveFileDialog1.ShowDialog();
            strSaveFile = SaveFileDialog1.FileName;

            if (strSaveFile == "")
            {
                return;
            }

            XslCompiledTransform objXSLTransform = new XslCompiledTransform();

            objXSLTransform.Load(GlobalOptions.ApplicationPath() + Path.DirectorySeparatorChar + "export" + Path.DirectorySeparatorChar + cboXSLT.Text + ".xsl"); // Use the path for the export sheet.

            XmlWriterSettings objSettings = objXSLTransform.OutputSettings.Clone();

            objSettings.CheckCharacters  = false;
            objSettings.ConformanceLevel = ConformanceLevel.Fragment;

            MemoryStream objStream = new MemoryStream();
            XmlWriter    objWriter = XmlWriter.Create(objStream, objSettings);

            objXSLTransform.Transform(_objCharacterXML, null, objWriter);
            objStream.Position = 0;

            // Read in the resulting code and pass it to the browser.
            StreamReader objReader = new StreamReader(objStream);

            File.WriteAllText(strSaveFile, objReader.ReadToEnd());             // Change this to a proper path.

            this.DialogResult = DialogResult.OK;
        }
示例#6
0
        private void cmdCompressData_Click(object sender, EventArgs e)
        {
            OmaeHelper objHelper = new OmaeHelper();

            foreach (string strFile in Directory.GetFiles(Path.Combine(GlobalOptions.ApplicationPath(), "data"), "*.xml"))
            {
                byte[] bytFile = File.ReadAllBytes(strFile);
                bytFile = objHelper.Compress(bytFile);
                File.WriteAllBytes(strFile.Replace(".xml", ".zip"), bytFile);
            }

            MessageBox.Show("Done");
        }
示例#7
0
        /// <summary>
        /// Decompress multiple files from a single zip file.
        /// </summary>
        /// <param name="bytBuffer">Byte array that contains the zip file.</param>
        public void DecompressNPCs(byte[] bytBuffer)
        {
            string strFilePath = Path.Combine(GlobalOptions.ApplicationPath(), "saves");

            // If the directory does not exist, create it.
            if (!Directory.Exists(strFilePath))
            {
                Directory.CreateDirectory(strFilePath);
            }

            MemoryStream objStream = new MemoryStream();

            objStream.Write(bytBuffer, 0, bytBuffer.Length);
            Package objPackage = ZipPackage.Open(objStream, FileMode.Open, FileAccess.Read);

            foreach (PackagePart objPart in objPackage.GetParts())
            {
                string strTarget = Path.Combine(strFilePath, objPart.Uri.ToString().Replace('_', ' '));

                Stream objSource = objPart.GetStream(FileMode.Open, FileAccess.Read);

                string[] strDirectory = strTarget.Split('/');
                if (!strDirectory[1].EndsWith(".chum"))
                {
                    if (!Directory.Exists(Path.Combine(strFilePath, strDirectory[1])))
                    {
                        Directory.CreateDirectory(Path.Combine(strFilePath, strDirectory[1]));
                    }
                }
                if (!strDirectory[2].EndsWith(".chum"))
                {
                    if (!Directory.Exists(Path.Combine(strFilePath, strDirectory[1] + Path.DirectorySeparatorChar + strDirectory[2])))
                    {
                        Directory.CreateDirectory(Path.Combine(strFilePath, strDirectory[1] + Path.DirectorySeparatorChar + strDirectory[2]));
                    }
                }

                Stream objDestination = File.OpenWrite(strFilePath + strTarget.Replace('/', Path.DirectorySeparatorChar));
                byte[] bytFileBuffer  = new byte[100000];
                int    intRead;
                intRead = objSource.Read(bytFileBuffer, 0, bytFileBuffer.Length);
                while (intRead > 0)
                {
                    objDestination.Write(bytFileBuffer, 0, intRead);
                    intRead = objSource.Read(bytFileBuffer, 0, bytFileBuffer.Length);
                }
                objDestination.Close();
                objSource.Close();
            }
        }
示例#8
0
        /// <summary>
        /// Load the non-English strings from the translation file.
        /// </summary>
        public static void LoadTranslatedString()
        {
            string strFilePath = "";

            try
            {
                XmlDocument objLanguageDocument = new XmlDocument();
                strFilePath = Path.Combine(GlobalOptions.ApplicationPath(), "lang");
                strFilePath = Path.Combine(strFilePath, GlobalOptions.Instance.Language + ".xml");
                objLanguageDocument.Load(strFilePath);
                _objXmlDocument.Load(strFilePath);
                foreach (XmlNode objNode in objLanguageDocument.SelectNodes("/chummer/strings/string"))
                {
                    // Look for the English version of the found string. If it has been found, replace the English contents with the contents from this file.
                    // If the string was not found, then someone has inserted a Key that should not exist and is ignored.
                    try
                    {
                        if (_objDictionary[objNode["key"].InnerText] != null)
                        {
                            _objDictionary[objNode["key"].InnerText] = objNode["text"].InnerText;
                        }
                    }
                    catch
                    {
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Language file " + strFilePath + " could not be loaded.", "Cannot Load Language", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Check to see if the data translation file for the selected language exists.
            string strDataPath = Path.Combine(GlobalOptions.ApplicationPath(), "lang");

            strDataPath = Path.Combine(strDataPath, GlobalOptions.Instance.Language + "_data.xml");
            if (File.Exists(strDataPath))
            {
                try
                {
                    _objXmlDataDocument = new XmlDocument();
                    _objXmlDataDocument.Load(strDataPath);
                }
                catch
                {
                    // Failing to load the data translation file should not render the application unusable.
                }
            }
        }
示例#9
0
 private void frmHistory_Load(object sender, EventArgs e)
 {
     // Display the contents of the changelog.txt file in the TextBox.
     try
     {
         txtRevisionHistory.Text            = File.ReadAllText(GlobalOptions.ApplicationPath() + Path.DirectorySeparatorChar + "changelog.txt");
         txtRevisionHistory.SelectionStart  = 0;
         txtRevisionHistory.SelectionLength = 0;
     }
     catch
     {
         MessageBox.Show(LanguageManager.Instance.GetString("Message_History_FileNotFound"), LanguageManager.Instance.GetString("MessageTitle_FileNotFound"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
         this.Close();
     }
 }
示例#10
0
        private void frmExport_Load(object sender, EventArgs e)
        {
            // Populate the XSLT list with all of the XSL files found in the sheets directory.
            foreach (string strFile in Directory.GetFiles(GlobalOptions.ApplicationPath() + Path.DirectorySeparatorChar + "export"))
            {
                // Only show files that end in .xsl. Do not include files that end in .xslt since they are used as "hidden" reference sheets (hidden because they are partial templates that cannot be used on their own).
                if (!strFile.EndsWith(".xslt") && strFile.EndsWith(".xsl"))
                {
                    string strFileName = strFile.Replace(GlobalOptions.ApplicationPath() + Path.DirectorySeparatorChar + "export" + Path.DirectorySeparatorChar, string.Empty).Replace(".xsl", string.Empty);
                    cboXSLT.Items.Add(strFileName);
                }
            }

            if (cboXSLT.Items.Count > 0)
            {
                cboXSLT.SelectedIndex = 0;
            }
        }
示例#11
0
        private void frmViewer_FormClosing(object sender, FormClosingEventArgs e)
        {
            // Remove the mugshots directory when the form closes.
            try
            {
                Directory.Delete(GlobalOptions.ApplicationPath() + Path.DirectorySeparatorChar + "mugshots", true);
            }
            catch
            {
            }

            // Clear the reference to the character's Print window.
            if (_lstCharacters.Count > 0)
            {
                foreach (Character objCharacter in _lstCharacters)
                {
                    objCharacter.PrintWindow = null;
                }
            }
        }
示例#12
0
		private void frmOmaeUploadData_Load(object sender, EventArgs e)
		{
			// Populate the CheckedListBox with the list of custom and override files in the user's data directory.
            string strFilePath = Path.Combine(GlobalOptions.ApplicationPath(), "data");
			foreach (string strFile in Directory.GetFiles(strFilePath, "custom*_*.xml"))
			{
				TreeNode objNode = new TreeNode();
				objNode.Tag = strFile;
				objNode.Text = strFile.Replace(strFilePath + Path.DirectorySeparatorChar, string.Empty);
				treFiles.Nodes.Add(objNode);
			}

			foreach (string strFile in Directory.GetFiles(strFilePath, "override*_*.xml"))
			{
				TreeNode objNode = new TreeNode();
				objNode.Tag = strFile;
				objNode.Text = strFile.Replace(strFilePath + Path.DirectorySeparatorChar, string.Empty);
				treFiles.Nodes.Add(objNode);
			}
		}
示例#13
0
        private void frmSelectSetting_Load(object sender, EventArgs e)
        {
            // Build the list of XML files found in the settings directory.
            List <ListItem> lstSettings = new List <ListItem>();

            foreach (string strFileName in Directory.GetFiles(Path.Combine(GlobalOptions.ApplicationPath(), "settings"), "*.xml"))
            {
                // Remove the path from the file name.
                string strSettingsFile = strFileName;
                strSettingsFile = strSettingsFile.Replace(Path.Combine(GlobalOptions.ApplicationPath(), "settings"), string.Empty);
                strSettingsFile = strSettingsFile.Replace(Path.DirectorySeparatorChar, ' ').Trim();

                // Load the file so we can get the Setting name.
                XmlDocument objXmlDocument = new XmlDocument();
                objXmlDocument.Load(strFileName);
                string strSettingsName = objXmlDocument.SelectSingleNode("/settings/name").InnerText;

                ListItem objItem = new ListItem();
                objItem.Value = strSettingsFile;
                objItem.Name  = strSettingsName;

                lstSettings.Add(objItem);
            }
            SortListItem objSort = new SortListItem();

            lstSettings.Sort(objSort.Compare);
            cboSetting.DataSource    = lstSettings;
            cboSetting.ValueMember   = "Value";
            cboSetting.DisplayMember = "Name";

            // Attempt to make default.xml the default one. If it could not be found in the list, select the first item instead.
            cboSetting.SelectedIndex = cboSetting.FindStringExact("Default Settings");
            if (cboSetting.SelectedIndex == -1)
            {
                cboSetting.SelectedIndex = 0;
            }
        }
示例#14
0
        /// <summary>
        /// Run through the files that were downloaded and make sure their size is more than 0 bytes.
        /// </summary>
        private bool ValidateFiles()
        {
            bool   blnReturn   = true;
            string strFilePath = GlobalOptions.ApplicationPath() + Path.DirectorySeparatorChar;

            // Loop through all of the root-level nodes in the update tree.
            foreach (TreeNode nodRoot in treeUpdate.Nodes)
            {
                // Loop through each of the child nodes.
                foreach (TreeNode nodNode in nodRoot.Nodes)
                {
                    if (nodNode.Checked)
                    {
                        FileInfo objInfo = new FileInfo(strFilePath + nodNode.Tag.ToString().Replace('/', Path.DirectorySeparatorChar));
                        if (objInfo.Length == 0)
                        {
                            blnReturn = false;
                        }
                    }
                }
            }

            return(blnReturn && _blnExeDownloadSuccess);
        }
示例#15
0
		private void cmdUpload_Click(object sender, EventArgs e)
		{
			// Make sure a name has been entered.
			if (txtName.Text == "")
			{
				MessageBox.Show(LanguageManager.Instance.GetString("Message_OmaeUpload_DataName"), LanguageManager.Instance.GetString("MessageTitle_OmaeUpload_DataName"), MessageBoxButtons.OK, MessageBoxIcon.Information);
				return;
			}

			// Make sure there is at least some sort of description.
			if (txtDescription.Text.Trim() == "")
			{
				MessageBox.Show(LanguageManager.Instance.GetString("Message_OameUpload_DataDescription"), LanguageManager.Instance.GetString("MessageTitle_OmaeUpload_DataDescription"), MessageBoxButtons.OK, MessageBoxIcon.Information);
				return;
			}

			// Make sure at least 1 file is selected.
			int intCount = 0;
			foreach (TreeNode objNode in treFiles.Nodes)
			{
				if (objNode.Checked)
					intCount++;
			}

			if (intCount == 0)
			{
				MessageBox.Show(LanguageManager.Instance.GetString("Message_OmaeUpload_DataSelectFiles"), LanguageManager.Instance.GetString("MessageTitle_OmaeUpload_SelectFile"), MessageBoxButtons.OK, MessageBoxIcon.Information);
				return;
			}
			
			bool blnSuccess = false;

            string strFilePath = Path.Combine(GlobalOptions.ApplicationPath(), "data");
			XmlDocument objXmlBooks = new XmlDocument();
			objXmlBooks.Load(Path.Combine(strFilePath, "books.xml"));

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

			// Run through all of the selected items. Create a list of the <source> items seen and make sure they're available in the core files or included in the user's selected item.
			foreach (TreeNode objNode in treFiles.Nodes)
			{
				if (objNode.Checked)
				{
					XmlDocument objXmlDocument = new XmlDocument();
					objXmlDocument.Load(objNode.Tag.ToString());

					XmlNodeList objRootList = objXmlDocument.SelectNodes("/chummer");
					foreach (XmlNode objXmlGroup in objRootList[0])
					{
						foreach (XmlNode objXmlNode in objXmlGroup.ChildNodes)
						{
							if (objXmlNode["source"] != null)
							{
								// Look to see if this sourcebook is already in the list. If not, add it.
								bool blnFound = false;
								foreach (string strSource in lstSource)
								{
									if (strSource == objXmlNode["source"].InnerText)
									{
										blnFound = true;
										break;
									}
								}
								if (!blnFound)
									lstSource.Add(objXmlNode["source"].InnerText);
							}
						}
					}
				}
			}

			// Now that we have the list of used sourcebooks, check the books file for the items.
			for (int i = 0; i <= lstSource.Count - 1; i++)
			{
				string strSource = lstSource[i];
				if (strSource != "")
				{
					XmlNode objNode = objXmlBooks.SelectSingleNode("/chummer/books/book[code = \"" + strSource + "\"]");
					if (objNode != null)
						lstSource[i] = "";
				}
			}

			// Check any custom book files the user selected.
			foreach (TreeNode objNode in treFiles.Nodes)
			{
				if (objNode.Checked && objNode.Tag.ToString().EndsWith("books.xml"))
				{
					XmlDocument objXmlCustom = new XmlDocument();
					objXmlCustom.Load(objNode.Tag.ToString());

					for (int i = 0; i <= lstSource.Count - 1; i++)
					{
						string strSource = lstSource[i];
						if (strSource != "")
						{
							XmlNode objBookNode = objXmlCustom.SelectSingleNode("/chummer/books/book[code = \"" + strSource + "\"]");
							if (objBookNode != null)
								lstSource[i] = "";
						}
					}
				}
			}

			// With all of the books checked, run through the list one more time and display an error if there are still any that were not found.
			string strMessage = "";
			foreach (string strSource in lstSource)
			{
				if (strSource != "")
					strMessage += "\n\t" + strSource;
			}
			if (strMessage != string.Empty)
			{
				MessageBox.Show("The following sourcebooks could not be found in the core data files or any of the data files you have selected:" + strMessage);
				return;
			}

			// Everything is OK, so zip up the selected files.
			List<string> lstFiles = new List<string>();
			string strFilesIncluded = "";
			foreach (TreeNode objNode in treFiles.Nodes)
			{
				if (objNode.Checked)
				{
					lstFiles.Add(objNode.Tag.ToString());
					strFilesIncluded += objNode.Text + ",";
				}
			}
			byte[] bytFile = _objOmaeHelper.CompressMutiple(lstFiles);

			// Make sure the file doesn't exceed 250K in size (256,000 bytes).
			if (bytFile.Length > 256000)
			{
				MessageBox.Show(LanguageManager.Instance.GetString("Message_OmaeUpload_FileTooLarge"), LanguageManager.Instance.GetString("MessageTitle_OmaeUpload_FileTooLarge"), MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}

			// Upload the file.
			omaeSoapClient objService = _objOmaeHelper.GetOmaeService();
			try
			{
				cmdUpload.Enabled = false;
				txtDescription.Enabled = false;
				txtName.Enabled = false;
				if (objService.UploadDataFile(_strUserName, _intDataID, txtName.Text, txtDescription.Text, strFilesIncluded, bytFile))
				{
					blnSuccess = true;
					MessageBox.Show(LanguageManager.Instance.GetString("Message_OmaeUpload_UploadComplete"), LanguageManager.Instance.GetString("MessageTitle_OmaeUpload_UploadComplete"), MessageBoxButtons.OK, MessageBoxIcon.Information);
				}
				else
				{
					MessageBox.Show(LanguageManager.Instance.GetString("Message_OmaeUpload_UploadFailed"), LanguageManager.Instance.GetString("MessageTitle_OmaeUpload_UploadFailed"), MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
			catch (EndpointNotFoundException)
			{
				MessageBox.Show(NO_CONNECTION_MESSAGE, NO_CONNECTION_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			objService.Close();
			cmdUpload.Enabled = true;
			txtDescription.Enabled = true;
			txtName.Enabled = true;

			if (blnSuccess)
				this.DialogResult = DialogResult.OK;

			//_objOmaeHelper.DecompressMultiple(bytFile);
		}
示例#16
0
        /// <summary>
        /// Check the Keys in the selected language file against the English version.
        /// </summary>
        /// <param name="strLanguage">Language to check.</param>
        public void VerifyStrings(string strLanguage)
        {
            // Load the English version.
            List <LanguageString> lstEnglish         = new List <LanguageString>();
            XmlDocument           objEnglishDocument = new XmlDocument();
            string strFilePath = Path.Combine(GlobalOptions.ApplicationPath(), "lang");

            strFilePath = Path.Combine(strFilePath, "en-us.xml");
            objEnglishDocument.Load(strFilePath);
            foreach (XmlNode objNode in objEnglishDocument.SelectNodes("/chummer/strings/string"))
            {
                LanguageString objString = new LanguageString();
                objString.Key  = objNode["key"].InnerText;
                objString.Text = objNode["text"].InnerText;
                lstEnglish.Add(objString);
            }

            // Load the selected language version.
            List <LanguageString> lstLanguage         = new List <LanguageString>();
            XmlDocument           objLanguageDocument = new XmlDocument();
            string strLangPath = Path.Combine(GlobalOptions.ApplicationPath(), "lang");

            strLangPath = Path.Combine(strLangPath, strLanguage + ".xml");
            objLanguageDocument.Load(strLangPath);
            foreach (XmlNode objNode in objLanguageDocument.SelectNodes("/chummer/strings/string"))
            {
                LanguageString objString = new LanguageString();
                objString.Key  = objNode["key"].InnerText;
                objString.Text = objNode["text"].InnerText;
                lstLanguage.Add(objString);
            }

            string strMessage = "";

            // Check for strings that are in the English file but not in the selected language file.
            foreach (LanguageString objString in lstEnglish)
            {
                LanguageString objFindString = lstLanguage.Find(objItem => objItem.Key == objString.Key);
                if (objFindString == null)
                {
                    strMessage += "\nMissing String: " + objString.Key;
                }
            }
            // Check for strings that are not in the English file but are in the selected language file (someone has put in Keys that they shouldn't have which are ignored).
            foreach (LanguageString objString in lstLanguage)
            {
                LanguageString objFindString = lstEnglish.Find(objItem => objItem.Key == objString.Key);
                if (objFindString == null)
                {
                    strMessage += "\nUnused String: " + objString.Key;
                }
            }

            // Display the message.
            if (strMessage != "")
            {
                MessageBox.Show(strMessage, "Language File Contents", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Language file is OK.", "Language File Contents", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
示例#17
0
        /// <summary>
        /// Verify the contents of the language data translation file.
        /// </summary>
        /// <param name="strLanguage">Language to check.</param>
        /// <param name="lstBooks">List of books.</param>
        public void Verify(string strLanguage, List <string> lstBooks)
        {
            XmlDocument objLanguageDoc = new XmlDocument();
            string      strFilePath    = Path.Combine(GlobalOptions.ApplicationPath(), "lang");

            strFilePath = Path.Combine(strFilePath, strLanguage + "_data.xml");
            objLanguageDoc.Load(strFilePath);

            string strLangPath = Path.Combine(GlobalOptions.ApplicationPath(), "lang");

            strLangPath = Path.Combine(strLangPath, "results_" + strLanguage + ".xml");
            FileStream    objStream = new FileStream(strLangPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.Unicode);

            objWriter.Formatting  = Formatting.Indented;
            objWriter.Indentation = 1;
            objWriter.IndentChar  = '\t';

            objWriter.WriteStartDocument();
            // <results>
            objWriter.WriteStartElement("results");

            string strPath = Path.Combine(GlobalOptions.ApplicationPath(), "data");

            foreach (string strFile in Directory.GetFiles(strPath, "*.xml"))
            {
                string strPathReplace = strPath + Path.DirectorySeparatorChar;
                string strFileName    = strFile.Replace(strPathReplace, string.Empty);

                // Do not bother to check custom files.
                if (!strFileName.StartsWith("custom") && !strFile.StartsWith("override") && !strFile.Contains("packs.xml") && !strFile.Contains("ranges.xml"))
                {
                    // Load the current English file.
                    XmlDocument objEnglishDoc = new XmlDocument();
                    objEnglishDoc = Load(strFile.Replace(strPathReplace, string.Empty));
                    XmlNode objEnglishRoot = objEnglishDoc.SelectSingleNode("/chummer");

                    // First pass: make sure the document exists.
                    bool    blnExists       = false;
                    XmlNode objLanguageRoot = objLanguageDoc.SelectSingleNode("/chummer/chummer[@file = \"" + strFileName + "\"]");
                    if (objLanguageRoot != null)
                    {
                        blnExists = true;
                    }

                    // <file name="x" exists="y">
                    objWriter.WriteStartElement("file");
                    objWriter.WriteAttributeString("name", strFileName);
                    objWriter.WriteAttributeString("exists", blnExists.ToString());

                    if (blnExists)
                    {
                        foreach (XmlNode objType in objEnglishRoot.ChildNodes)
                        {
                            objWriter.WriteStartElement(objType.Name);
                            foreach (XmlNode objChild in objType.ChildNodes)
                            {
                                // If the Node has a source element, check it and see if it's in the list of books that were specified.
                                // This is done since not all of the books are available in every language or the user may only wish to verify the content of certain books.
                                bool blnContinue = false;
                                if (objChild["source"] != null)
                                {
                                    foreach (string strBook in lstBooks)
                                    {
                                        if (strBook == objChild["source"].InnerText)
                                        {
                                            blnContinue = true;
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    blnContinue = true;
                                }

                                if (blnContinue)
                                {
                                    if (objType.Name != "version" && !((objType.Name == "costs" || objType.Name == "safehousecosts") && strFile.EndsWith("lifestyles.xml")))
                                    {
                                        // Look for a matching entry in the Language file.
                                        if (objChild["id"] != null)
                                        {
                                            XmlNode objNode = objLanguageRoot.SelectSingleNode(objType.Name + "/" + objChild.Name + "[id = \"" + objChild["id"].InnerText + "\"]");
                                            if (objNode != null)
                                            {
                                                // A match was found, so see what elements, if any, are missing.
                                                bool blnTranslate    = false;
                                                bool blnAltPage      = false;
                                                bool blnAdvantage    = false;
                                                bool blnDisadvantage = false;

                                                if (objChild.HasChildNodes)
                                                {
                                                    if (objNode["translate"] != null)
                                                    {
                                                        blnTranslate = true;
                                                    }

                                                    // Do not mark page as missing if the original does not have it.
                                                    if (objChild["page"] != null)
                                                    {
                                                        if (objNode["page"] != null)
                                                        {
                                                            blnAltPage = true;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        blnAltPage = true;
                                                    }

                                                    if (strFile.EndsWith("mentors.xml") || strFile.EndsWith("paragons.xml"))
                                                    {
                                                        if (objNode["advantage"] != null)
                                                        {
                                                            blnAdvantage = true;
                                                        }
                                                        if (objNode["disadvantage"] != null)
                                                        {
                                                            blnDisadvantage = true;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        blnAdvantage    = true;
                                                        blnDisadvantage = true;
                                                    }
                                                }
                                                else
                                                {
                                                    blnAltPage = true;
                                                    if (objNode.Attributes["translate"] != null)
                                                    {
                                                        blnTranslate = true;
                                                    }
                                                }

                                                // At least one pice of data was missing so write out the result node.
                                                if (!blnTranslate || !blnAltPage || !blnAdvantage || !blnDisadvantage)
                                                {
                                                    // <results>
                                                    objWriter.WriteStartElement(objChild.Name);
                                                    objWriter.WriteAttributeString("exists", "True");
                                                    objWriter.WriteElementString("id", objChild["id"].InnerText);
                                                    if (!blnTranslate)
                                                    {
                                                        objWriter.WriteElementString("missing", "translate");
                                                    }
                                                    if (!blnAltPage)
                                                    {
                                                        objWriter.WriteElementString("missing", "page");
                                                    }
                                                    if (!blnAdvantage)
                                                    {
                                                        objWriter.WriteElementString("missing", "advantage");
                                                    }
                                                    if (!blnDisadvantage)
                                                    {
                                                        objWriter.WriteElementString("missing", "disadvantage");
                                                    }
                                                    // </results>
                                                    objWriter.WriteEndElement();
                                                }
                                            }
                                            else
                                            {
                                                // No match was found, so write out that the data item is missing.
                                                // <result>
                                                objWriter.WriteStartElement(objChild.Name);
                                                objWriter.WriteAttributeString("exists", "False");
                                                objWriter.WriteElementString("id", objChild["id"].InnerText);
                                                // </result>
                                                objWriter.WriteEndElement();
                                            }

                                            if (strFileName == "metatypes.xml")
                                            {
                                                if (objChild["metavariants"] != null)
                                                {
                                                    foreach (XmlNode objMetavariant in objChild.SelectNodes("metavariants/metavariant"))
                                                    {
                                                        XmlNode objTranslate = objLanguageRoot.SelectSingleNode("metatypes/metatype[id = \"" + objChild["id"].InnerText + "\"]/metavariants/metavariant[id = \"" + objMetavariant["id"].InnerText + "\"]");
                                                        if (objTranslate != null)
                                                        {
                                                            bool blnTranslate = false;
                                                            bool blnAltPage   = false;

                                                            if (objTranslate["translate"] != null)
                                                            {
                                                                blnTranslate = true;
                                                            }
                                                            if (objTranslate["page"] != null)
                                                            {
                                                                blnAltPage = true;
                                                            }

                                                            // Item exists, so make sure it has its translate attribute populated.
                                                            if (!blnTranslate || !blnAltPage)
                                                            {
                                                                // <result>
                                                                objWriter.WriteStartElement("metavariants");
                                                                objWriter.WriteStartElement("metavariant");
                                                                objWriter.WriteAttributeString("exists", "True");
                                                                objWriter.WriteElementString("id", objMetavariant["id"].InnerText);
                                                                if (!blnTranslate)
                                                                {
                                                                    objWriter.WriteElementString("missing", "translate");
                                                                }
                                                                if (!blnAltPage)
                                                                {
                                                                    objWriter.WriteElementString("missing", "page");
                                                                }
                                                                objWriter.WriteEndElement();
                                                                // </result>
                                                                objWriter.WriteEndElement();
                                                            }
                                                        }
                                                        else
                                                        {
                                                            // <result>
                                                            objWriter.WriteStartElement("metavariants");
                                                            objWriter.WriteStartElement("metavariant");
                                                            objWriter.WriteAttributeString("exists", "False");
                                                            objWriter.WriteElementString("name", objMetavariant.InnerText);
                                                            objWriter.WriteEndElement();
                                                            // </result>
                                                            objWriter.WriteEndElement();
                                                        }
                                                    }
                                                }
                                            }

                                            if (strFile == "martialarts.xml")
                                            {
                                                if (objChild["advantages"] != null)
                                                {
                                                    foreach (XmlNode objAdvantage in objChild.SelectNodes("advantages/advantage"))
                                                    {
                                                        XmlNode objTranslate = objLanguageRoot.SelectSingleNode("martialarts/martialart[id = \"" + objChild["id"].InnerText + "\"]/advantages/advantage[. = \"" + objAdvantage.InnerText + "\"]");
                                                        if (objTranslate != null)
                                                        {
                                                            // Item exists, so make sure it has its translate attribute populated.
                                                            if (objTranslate.Attributes["translate"] == null)
                                                            {
                                                                // <result>
                                                                objWriter.WriteStartElement("martialarts");
                                                                objWriter.WriteStartElement("advantage");
                                                                objWriter.WriteAttributeString("exists", "True");
                                                                objWriter.WriteElementString("name", objAdvantage.InnerText);
                                                                objWriter.WriteElementString("missing", "translate");
                                                                objWriter.WriteEndElement();
                                                                // </result>
                                                                objWriter.WriteEndElement();
                                                            }
                                                        }
                                                        else
                                                        {
                                                            // <result>
                                                            objWriter.WriteStartElement("martialarts");
                                                            objWriter.WriteStartElement("advantage");
                                                            objWriter.WriteAttributeString("exists", "False");
                                                            objWriter.WriteElementString("name", objAdvantage.InnerText);
                                                            objWriter.WriteEndElement();
                                                            // </result>
                                                            objWriter.WriteEndElement();
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        else if (objChild.InnerText != null)
                                        {
                                            // The item does not have a name which means it should have a translate Attribute instead.
                                            XmlNode objNode = objLanguageRoot.SelectSingleNode(objType.Name + "/" + objChild.Name + "[. = \"" + objChild.InnerText + "\"]");
                                            if (objNode != null)
                                            {
                                                // Make sure the translate attribute is populated.
                                                if (objNode.Attributes["translate"] == null)
                                                {
                                                    // <result>
                                                    objWriter.WriteStartElement(objChild.Name);
                                                    objWriter.WriteAttributeString("exists", "True");
                                                    objWriter.WriteElementString("id", objChild.InnerText);
                                                    objWriter.WriteElementString("missing", "translate");
                                                    // </result>
                                                    objWriter.WriteEndElement();
                                                }
                                            }
                                            else
                                            {
                                                // No match was found, so write out that the data item is missing.
                                                // <result>
                                                objWriter.WriteStartElement(objChild.Name);
                                                objWriter.WriteAttributeString("exists", "False");
                                                objWriter.WriteElementString("id", objChild.InnerText);
                                                // </result>
                                                objWriter.WriteEndElement();
                                            }
                                        }
                                    }
                                }
                            }
                            objWriter.WriteEndElement();
                        }

                        // Now loop through the translation file and determine if there are any entries in there that are not part of the base content.
                        foreach (XmlNode objType in objLanguageRoot.ChildNodes)
                        {
                            foreach (XmlNode objChild in objType.ChildNodes)
                            {
                                // Look for a matching entry in the English file.
                                if (objChild["id"] != null)
                                {
                                    XmlNode objNode = objEnglishRoot.SelectSingleNode("/chummer/" + objType.Name + "/" + objChild.Name + "[id = \"" + objChild["id"].InnerText + "\"]");
                                    if (objNode == null)
                                    {
                                        // <noentry>
                                        objWriter.WriteStartElement("noentry");
                                        objWriter.WriteStartElement(objChild.Name);
                                        objWriter.WriteElementString("id", objChild["id"].InnerText);
                                        objWriter.WriteEndElement();
                                        // </noentry>
                                        objWriter.WriteEndElement();
                                    }
                                }
                            }
                        }
                    }

                    // </file>
                    objWriter.WriteEndElement();
                }
            }

            // </results>
            objWriter.WriteEndElement();
            objWriter.WriteEndDocument();
            objWriter.Close();
            objStream.Close();
        }
示例#18
0
        /// <summary>
        /// Load the selected XML file and its associated custom file.
        /// </summary>
        /// <param name="strFileName">Name of the XML file to load.</param>
        public XmlDocument Load(string strFileName)
        {
            string strPath = Path.Combine(GlobalOptions.ApplicationPath(), "data");

            strPath = Path.Combine(strPath, strFileName);
            DateTime datDate = File.GetLastWriteTime(strPath);

            // Look to see if this XmlDocument is already loaded.
            bool         blnFound     = false;
            XmlReference objReference = new XmlReference();

            foreach (XmlReference objCurrentReference in _lstXmlDocuments)
            {
                if (objCurrentReference.FileName == strFileName)
                {
                    objReference = objCurrentReference;
                    blnFound     = true;
                    break;
                }
            }

            bool blnLoadFile = false;

            if (!blnFound)
            {
                // The file was not found in the reference list, so it must be loaded.
                blnLoadFile = true;
                _lstXmlDocuments.Add(objReference);
            }
            else
            {
                // The file was found in the List, so check the last write time.
                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 = new XmlDocument();
            // write the root chummer node.
            XmlNode objCont = objDoc.CreateElement("chummer");

            objDoc.AppendChild(objCont);

            XmlDocument objXmlFile = new XmlDocument();
            XmlNodeList objList;

            if (blnLoadFile)
            {
                // Load the base file and retrieve all of the child nodes.
                objXmlFile.Load(strPath);
                objList = objXmlFile.SelectNodes("/chummer/*");
                foreach (XmlNode objNode in objList)
                {
                    // Append the entire child node to the new document.
                    XmlNode objImported = objDoc.ImportNode(objNode, true);
                    objDoc.DocumentElement.AppendChild(objImported);
                }

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

                // 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 this is a translatable item, find the proper node and add/update this information.
                                    if (objChild["translate"] != null)
                                    {
                                        XmlNode objItem = objDoc.SelectSingleNode("/chummer/" + objType.Name + "/" + objChild.Name + "[id = \"" + objChild["id"].InnerXml + "\"]");
                                        if (objItem != null)
                                        {
                                            objItem.InnerXml += "<translate>" + objChild["translate"].InnerXml + "</translate>";
                                        }
                                    }
                                    if (objChild["page"] != null)
                                    {
                                        XmlNode objItem = objDoc.SelectSingleNode("/chummer/" + objType.Name + "/" + objChild.Name + "[id = \"" + objChild["id"].InnerXml + "\"]");
                                        if (objItem != null)
                                        {
                                            objItem.InnerXml += "<altpage>" + objChild["page"].InnerXml + "</altpage>";
                                        }
                                    }
                                    if (objChild["code"] != null)
                                    {
                                        XmlNode objItem = objDoc.SelectSingleNode("/chummer/" + objType.Name + "/" + objChild.Name + "[id = \"" + objChild["id"].InnerXml + "\"]");
                                        if (objItem != null)
                                        {
                                            objItem.InnerXml += "<altcode>" + objChild["code"].InnerXml + "</altcode>";
                                        }
                                    }
                                    if (objChild["advantage"] != null)
                                    {
                                        XmlNode objItem = objDoc.SelectSingleNode("/chummer/" + objType.Name + "/" + objChild.Name + "[id = \"" + objChild["id"].InnerXml + "\"]");
                                        if (objItem != null)
                                        {
                                            objItem.InnerXml += "<altadvantage>" + objChild["advantage"].InnerXml + "</altadvantage>";
                                        }
                                    }
                                    if (objChild["disadvantage"] != null)
                                    {
                                        XmlNode objItem = objDoc.SelectSingleNode("/chummer/" + objType.Name + "/" + objChild.Name + "[id = \"" + objChild["id"].InnerXml + "\"]");
                                        if (objItem != null)
                                        {
                                            objItem.InnerXml += "<altdisadvantage>" + objChild["disadvantage"].InnerXml + "</altdisadvantage>";
                                        }
                                    }
                                    if (objChild.Attributes != null)
                                    {
                                        // Handle Category name translations.
                                        if (objChild.Attributes["translate"] != null)
                                        {
                                            XmlNode objItem = objDoc.SelectSingleNode("/chummer/" + objType.Name + "/" + objChild.Name + "[. = \"" + objChild.InnerXml.Replace("&amp;", "&") + "\"]");
                                            if (objItem != null)
                                            {
                                                XmlElement objElement = (XmlElement)objItem;
                                                objElement.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)
                                                {
                                                    XmlNode objItem = objDoc.SelectSingleNode("/chummer/" + objType.Name + "/skill[name = \"" + objChild["name"].InnerXml + "\"]/specs/spec[. = \"" + objSpec.InnerXml + "\"]");
                                                    if (objItem != null)
                                                    {
                                                        XmlElement objElement = (XmlElement)objItem;
                                                        objElement.SetAttribute("translate", objSpec.Attributes["translate"].InnerXml);
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    // Check for Metavariant information.
                                    if (strFileName == "metatypes.xml")
                                    {
                                        if (objChild["metavariants"] != null)
                                        {
                                            foreach (XmlNode objMetavariant in objChild.SelectNodes("metavariants/metavariant"))
                                            {
                                                if (objMetavariant["translate"] != null)
                                                {
                                                    XmlNode objItem = objDoc.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + objChild["name"].InnerXml + "\"]/metavariants/metavariant[id = \"" + objMetavariant["id"].InnerXml + "\"]");
                                                    if (objItem != null)
                                                    {
                                                        objItem.InnerXml += "<translate>" + objMetavariant["translate"].InnerXml + "</translate>";
                                                    }
                                                }
                                                if (objMetavariant["altpage"] != null)
                                                {
                                                    XmlNode objItem = objDoc.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + objChild["name"].InnerXml + "\"]/metavariants/metavariant[id = \"" + objMetavariant["id"].InnerXml + "\"]");
                                                    if (objItem != null)
                                                    {
                                                        objItem.InnerXml += "<altpage>" + objMetavariant["page"].InnerXml + "</altpage>";
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    // Check for Martial Art Advantage information.
                                    if (strFileName == "martialarts.xml")
                                    {
                                        if (objChild["advantages"] != null)
                                        {
                                            foreach (XmlNode objAdvantage in objChild.SelectNodes("advantages/advantage"))
                                            {
                                                if (objAdvantage.Attributes["translate"] != null)
                                                {
                                                    XmlNode objItem = objDoc.SelectSingleNode("/chummer/martialarts/martialart[name = \"" + objChild["name"].InnerXml + "\"]/advantages/advantage[. = \"" + objAdvantage.InnerXml + "\"]");
                                                    if (objItem != null)
                                                    {
                                                        XmlElement objElement = (XmlElement)objItem;
                                                        objElement.SetAttribute("translate", objAdvantage.Attributes["translate"].InnerXml);
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    // Check for Mentor Spirit/Paragon choice information.
                                    if (strFileName == "mentors.xml" || strFileName == "paragons.xml")
                                    {
                                        if (objChild["choices"] != null)
                                        {
                                            foreach (XmlNode objChoice in objChild.SelectNodes("choices/choice"))
                                            {
                                                if (objChoice["translate"] != null)
                                                {
                                                    XmlNode objItem = objDoc.SelectSingleNode("/chummer/mentors/mentor[id = \"" + objChild["id"].InnerXml + "\"]/choices/choice[id = \"" + objChoice["id"].InnerXml + "\"]");
                                                    if (objItem != null)
                                                    {
                                                        objItem.InnerXml += "<translate>" + objChoice["translate"].InnerXml + "</translate>";
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                // Cache the merged document and its relevant information.
                objReference.FileDate   = datDate;
                objReference.FileName   = strFileName;
                objReference.XmlContent = objDoc;
            }
            else
            {
                // Pull the document from cache.
                objDoc = objReference.XmlContent;
            }

            // 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).
            XmlDocument objReturnDocument = new XmlDocument();

            objReturnDocument.LoadXml(objDoc.OuterXml);

            // Load any custom data files the user might have. Do not attempt this if we're loading the Improvements file.
            if (strFileName != "improvements.xml")
            {
                strPath = Path.Combine(GlobalOptions.ApplicationPath(), "data");
                foreach (string strFile in Directory.GetFiles(strPath, "custom*_" + strFileName))
                {
                    objXmlFile.Load(strFile);
                    objList = objXmlFile.SelectNodes("/chummer/*");
                    foreach (XmlNode objNode in objList)
                    {
                        // 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 field since this is what we must match on.
                            if (objChild["name"] != null)
                            {
                                XmlNodeList objNodeList = objReturnDocument.SelectNodes("/chummer/" + objChild.ParentNode.Name + "/" + objChild.Name + "[name = \"" + objChild["name"].InnerText + "\"]");
                                if (objNodeList.Count > 0)
                                {
                                    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.
                        XmlNode objImported = objReturnDocument.ImportNode(objNode, true);
                        objReturnDocument.DocumentElement.AppendChild(objImported);
                    }
                }
            }

            return(objReturnDocument);
        }
示例#19
0
        private void cmdOK_Click(object sender, EventArgs e)
        {
            // Make sure the suite and file name fields are populated.
            if (txtName.Text == "")
            {
                MessageBox.Show(LanguageManager.Instance.GetString("Message_CyberwareSuite_SuiteName"), LanguageManager.Instance.GetString("MessageTitle_CyberwareSuite_SuiteName"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (txtFileName.Text == "")
            {
                MessageBox.Show(LanguageManager.Instance.GetString("Message_CyberwareSuite_FileName"), LanguageManager.Instance.GetString("MessageTitle_CyberwareSuite_FileName"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // Make sure the file name starts with custom and ends with _cyberware.xml.
            if (!txtFileName.Text.StartsWith("custom") || !txtFileName.Text.EndsWith("_" + _strType + ".xml"))
            {
                MessageBox.Show(LanguageManager.Instance.GetString("Message_CyberwareSuite_InvalidFileName").Replace("{0}", _strType), LanguageManager.Instance.GetString("MessageTitle_CyberwareSuite_InvalidFileName"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // See if a Suite with this name already exists for the Custom category. This is done without the XmlManager since we need to check each file individually.
            XmlDocument objXmlDocument = new XmlDocument();
            XmlNodeList objXmlSuiteList;
            string      strCustomPath = Path.Combine(GlobalOptions.ApplicationPath(), "data");

            foreach (string strFile in Directory.GetFiles(strCustomPath, "custom*_" + _strType + ".xml"))
            {
                objXmlDocument.Load(strFile);
                objXmlSuiteList = objXmlDocument.SelectNodes("/chummer/suites/suite[name = \"" + txtName.Text + "\"]");
                if (objXmlSuiteList.Count > 0)
                {
                    MessageBox.Show(LanguageManager.Instance.GetString("Message_CyberwareSuite_DuplicateName").Replace("{0}", txtName.Text).Replace("{1}", strFile.Replace(strCustomPath + Path.DirectorySeparatorChar, string.Empty)), LanguageManager.Instance.GetString("MessageTitle_CyberwareSuite_DuplicateName"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }

            string strPath = Path.Combine(GlobalOptions.ApplicationPath(), "data");

            strPath = Path.Combine(strPath, txtFileName.Text);
            bool blnNewFile = !File.Exists(strPath);

            // If this is not a new file, read in the existing contents.
            XmlDocument objXmlCurrentDocument = new XmlDocument();

            if (!blnNewFile)
            {
                objXmlCurrentDocument.Load(strPath);
            }

            FileStream    objStream = new FileStream(strPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.Unicode);

            objWriter.Formatting  = Formatting.Indented;
            objWriter.Indentation = 1;
            objWriter.IndentChar  = '\t';
            objWriter.WriteStartDocument();

            // <chummer>
            objWriter.WriteStartElement("chummer");
            if (!blnNewFile)
            {
                // <cyberwares>
                objWriter.WriteStartElement(_strType + "s");
                XmlNodeList objXmlCyberwareList = objXmlCurrentDocument.SelectNodes("/chummer/" + _strType + "s");
                foreach (XmlNode objXmlCyberware in objXmlCyberwareList)
                {
                    objXmlCyberware.WriteContentTo(objWriter);
                }
                // </cyberwares>
                objWriter.WriteEndElement();
            }

            // <suites>
            objWriter.WriteStartElement("suites");

            // If this is not a new file, write out the current contents.
            if (!blnNewFile)
            {
                XmlNodeList objXmlCyberwareList = objXmlCurrentDocument.SelectNodes("/chummer/suites");
                foreach (XmlNode objXmlCyberware in objXmlCyberwareList)
                {
                    objXmlCyberware.WriteContentTo(objWriter);
                }
            }

            string strGrade = "";

            // Determine the Grade of Cyberware.
            foreach (Cyberware objCyberware in _objCharacter.Cyberware)
            {
                if (objCyberware.SourceType == _objSource)
                {
                    strGrade = objCyberware.Grade.ToString();
                    break;
                }
            }

            // <suite>
            objWriter.WriteStartElement("suite");
            // <name />
            objWriter.WriteElementString("name", txtName.Text);
            // <grade />
            objWriter.WriteElementString("grade", strGrade);
            // <cyberwares>
            objWriter.WriteStartElement(_strType + "s");

            // Write out the Cyberware.
            foreach (Cyberware objCyberware in _objCharacter.Cyberware)
            {
                if (objCyberware.SourceType == _objSource)
                {
                    // <cyberware>
                    objWriter.WriteStartElement(_strType);
                    objWriter.WriteElementString("name", objCyberware.Name);
                    if (objCyberware.Rating > 0)
                    {
                        objWriter.WriteElementString("rating", objCyberware.Rating.ToString());
                    }
                    // Write out child items.
                    if (objCyberware.Cyberwares.Count > 0)
                    {
                        // <cyberwares>
                        objWriter.WriteStartElement(_strType + "s");
                        foreach (Cyberware objChild in objCyberware.Cyberwares)
                        {
                            // Do not include items that come with the base item by default.
                            if (objChild.Capacity != "[*]")
                            {
                                objWriter.WriteStartElement(_strType);
                                objWriter.WriteElementString("name", objChild.Name);
                                if (objChild.Rating > 0)
                                {
                                    objWriter.WriteElementString("rating", objChild.Rating.ToString());
                                }
                                // </cyberware>
                                objWriter.WriteEndElement();
                            }
                        }
                        // </cyberwares>
                        objWriter.WriteEndElement();
                    }
                    // </cyberware>
                    objWriter.WriteEndElement();
                }
            }

            // </cyberwares>
            objWriter.WriteEndElement();
            // </suite>
            objWriter.WriteEndElement();
            // </chummer>
            objWriter.WriteEndElement();

            objWriter.WriteEndDocument();
            objWriter.Close();
            objStream.Close();

            MessageBox.Show(LanguageManager.Instance.GetString("Message_CyberwareSuite_SuiteCreated").Replace("{0}", txtName.Text), LanguageManager.Instance.GetString("MessageTitle_CyberwareSuite_SuiteCreated"), MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.DialogResult = DialogResult.OK;
        }
示例#20
0
        private void cmdOK_Click(object sender, EventArgs e)
        {
            // Make sure the kit and file name fields are populated.
            if (txtName.Text == "")
            {
                MessageBox.Show(LanguageManager.Instance.GetString("Message_CreatePACKSKit_KitName"), LanguageManager.Instance.GetString("MessageTitle_CreatePACKSKit_KitName"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (txtFileName.Text == "")
            {
                MessageBox.Show(LanguageManager.Instance.GetString("Message_CreatePACKSKit_FileName"), LanguageManager.Instance.GetString("MessageTitle_CreatePACKSKit_FileName"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // Make sure the file name starts with custom and ends with _packs.xml.
            if (!txtFileName.Text.StartsWith("custom") || !txtFileName.Text.EndsWith("_packs.xml"))
            {
                MessageBox.Show(LanguageManager.Instance.GetString("Message_CreatePACKSKit_InvalidFileName"), LanguageManager.Instance.GetString("MessageTitle_CreatePACKSKit_InvalidFileName"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // See if a Kit with this name already exists for the Custom category. This is done without the XmlManager since we need to check each file individually.
            XmlDocument objXmlDocument = new XmlDocument();
            string      strCustomPath  = Path.Combine(GlobalOptions.ApplicationPath(), "data");

            foreach (string strFile in Directory.GetFiles(strCustomPath, "custom*_packs.xml"))
            {
                objXmlDocument.Load(strFile);
                XmlNodeList objXmlPACKSList = objXmlDocument.SelectNodes("/chummer/packs/pack[name = \"" + txtName.Text + "\" and category = \"Custom\"]");
                if (objXmlPACKSList.Count > 0)
                {
                    MessageBox.Show(LanguageManager.Instance.GetString("Message_CreatePACKSKit_DuplicateName").Replace("{0}", txtName.Text).Replace("{1}", strFile.Replace(strCustomPath + Path.DirectorySeparatorChar, string.Empty)), LanguageManager.Instance.GetString("MessageTitle_CreatePACKSKit_DuplicateName"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }

            string strPath = Path.Combine(GlobalOptions.ApplicationPath(), "data");

            strPath = Path.Combine(strPath, txtFileName.Text);
            bool blnNewFile = !File.Exists(strPath);

            // If this is not a new file, read in the existing contents.
            XmlDocument objXmlCurrentDocument = new XmlDocument();

            if (!blnNewFile)
            {
                objXmlCurrentDocument.Load(strPath);
            }

            FileStream    objStream = new FileStream(strPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.Unicode);

            objWriter.Formatting  = Formatting.Indented;
            objWriter.Indentation = 1;
            objWriter.IndentChar  = '\t';
            objWriter.WriteStartDocument();

            // <chummer>
            objWriter.WriteStartElement("chummer");
            // <packs>
            objWriter.WriteStartElement("packs");

            // If this is not a new file, write out the current contents.
            if (!blnNewFile)
            {
                XmlNodeList objXmlNodeList = objXmlCurrentDocument.SelectNodes("/chummer/*");
                foreach (XmlNode objXmlNode in objXmlNodeList)
                {
                    objXmlNode.WriteContentTo(objWriter);
                }
            }

            // <pack>
            objWriter.WriteStartElement("pack");
            // <name />
            objWriter.WriteElementString("name", txtName.Text);
            // <category />
            objWriter.WriteElementString("category", "Custom");

            // Export Attributes.
            if (chkAttributes.Checked)
            {
                int intBOD = _objCharacter.BOD.Value - (_objCharacter.BOD.MetatypeMinimum - 1);
                int intAGI = _objCharacter.AGI.Value - (_objCharacter.AGI.MetatypeMinimum - 1);
                int intREA = _objCharacter.REA.Value - (_objCharacter.REA.MetatypeMinimum - 1);
                int intSTR = _objCharacter.STR.Value - (_objCharacter.STR.MetatypeMinimum - 1);
                int intCHA = _objCharacter.CHA.Value - (_objCharacter.CHA.MetatypeMinimum - 1);
                int intINT = _objCharacter.INT.Value - (_objCharacter.INT.MetatypeMinimum - 1);
                int intLOG = _objCharacter.LOG.Value - (_objCharacter.LOG.MetatypeMinimum - 1);
                int intWIL = _objCharacter.WIL.Value - (_objCharacter.WIL.MetatypeMinimum - 1);
                int intEDG = _objCharacter.EDG.Value - (_objCharacter.EDG.MetatypeMinimum - 1);
                int intMAG = _objCharacter.MAG.Value - (_objCharacter.MAG.MetatypeMinimum - 1);
                int intRES = _objCharacter.RES.Value - (_objCharacter.RES.MetatypeMinimum - 1);
                // <attributes>
                objWriter.WriteStartElement("attributes");
                objWriter.WriteElementString("bod", intBOD.ToString());
                objWriter.WriteElementString("agi", intAGI.ToString());
                objWriter.WriteElementString("rea", intREA.ToString());
                objWriter.WriteElementString("str", intSTR.ToString());
                objWriter.WriteElementString("cha", intCHA.ToString());
                objWriter.WriteElementString("int", intINT.ToString());
                objWriter.WriteElementString("log", intLOG.ToString());
                objWriter.WriteElementString("wil", intWIL.ToString());
                objWriter.WriteElementString("edg", intEDG.ToString());
                if (_objCharacter.MAGEnabled)
                {
                    objWriter.WriteElementString("mag", intMAG.ToString());
                }
                if (_objCharacter.RESEnabled)
                {
                    objWriter.WriteElementString("res", intRES.ToString());
                }
                // </attributes>
                objWriter.WriteEndElement();
            }

            // Export Qualities.
            if (chkQualities.Checked)
            {
                bool blnPositive = false;
                bool blnNegative = false;
                // Determine if Positive or Negative Qualities exist.
                foreach (Quality objQuality in _objCharacter.Qualities)
                {
                    if (objQuality.Type == QualityType.Positive)
                    {
                        blnPositive = true;
                    }
                    if (objQuality.Type == QualityType.Negative)
                    {
                        blnNegative = true;
                    }
                    if (blnPositive && blnNegative)
                    {
                        break;
                    }
                }
                // <qualities>
                objWriter.WriteStartElement("qualities");

                // Positive Qualities.
                if (blnPositive)
                {
                    // <positive>
                    objWriter.WriteStartElement("positive");
                    foreach (Quality objQuality in _objCharacter.Qualities)
                    {
                        if (objQuality.Type == QualityType.Positive)
                        {
                            objWriter.WriteStartElement("quality");
                            if (objQuality.Extra != "")
                            {
                                objWriter.WriteAttributeString("select", objQuality.Extra);
                            }
                            objWriter.WriteValue(objQuality.Name);
                            objWriter.WriteEndElement();
                        }
                    }
                    // </positive>
                    objWriter.WriteEndElement();
                }

                // Negative Qualities.
                if (blnPositive)
                {
                    // <negative>
                    objWriter.WriteStartElement("negative");
                    foreach (Quality objQuality in _objCharacter.Qualities)
                    {
                        if (objQuality.Type == QualityType.Negative)
                        {
                            objWriter.WriteStartElement("quality");
                            if (objQuality.Extra != "")
                            {
                                objWriter.WriteAttributeString("select", objQuality.Extra);
                            }
                            objWriter.WriteValue(objQuality.Name);
                            objWriter.WriteEndElement();
                        }
                    }
                    // </negative>
                    objWriter.WriteEndElement();
                }

                // </qualities>
                objWriter.WriteEndElement();
            }

            // Export Starting Nuyen.
            if (chkStartingNuyen.Checked)
            {
                int intNuyenBP = Convert.ToInt32(_objCharacter.NuyenBP);
                if (_objCharacter.BuildMethod == CharacterBuildMethod.Karma)
                {
                    intNuyenBP = Convert.ToInt32(Convert.ToDouble(intNuyenBP, GlobalOptions.Instance.CultureInfo) / 2.0);
                }
                objWriter.WriteElementString("nuyenbp", intNuyenBP.ToString());
            }

            // Export Active Skills.
            if (chkActiveSkills.Checked)
            {
                // <skills>
                objWriter.WriteStartElement("skills");
                // Active Skills.
                foreach (Skill objSkill in _objCharacter.Skills)
                {
                    if (!objSkill.KnowledgeSkill && !objSkill.IsGrouped && objSkill.Rating > 0)
                    {
                        // <skill>
                        objWriter.WriteStartElement("skill");
                        objWriter.WriteElementString("name", objSkill.Name);
                        objWriter.WriteElementString("rating", objSkill.Rating.ToString());
                        if (objSkill.Specialization != "")
                        {
                            objWriter.WriteElementString("spec", objSkill.Specialization);
                        }
                        // </skill>
                        objWriter.WriteEndElement();
                    }
                }

                // Skill Groups.
                foreach (SkillGroup objSkillGroup in _objCharacter.SkillGroups)
                {
                    if (!objSkillGroup.Broken && objSkillGroup.Rating > 0)
                    {
                        // <skillgroup>
                        objWriter.WriteStartElement("skillgroup");
                        objWriter.WriteElementString("name", objSkillGroup.Name);
                        objWriter.WriteElementString("rating", objSkillGroup.Rating.ToString());
                        // </skillgroup>
                        objWriter.WriteEndElement();
                    }
                }
                // </skills>
                objWriter.WriteEndElement();
            }

            // Export Knowledge Skills.
            if (chkKnowledgeSkills.Checked)
            {
                // <knowledgeskills>
                objWriter.WriteStartElement("knowledgeskills");
                // Active Skills.
                foreach (Skill objSkill in _objCharacter.Skills)
                {
                    if (objSkill.KnowledgeSkill)
                    {
                        // <skill>
                        objWriter.WriteStartElement("skill");
                        objWriter.WriteElementString("name", objSkill.Name);
                        objWriter.WriteElementString("rating", objSkill.Rating.ToString());
                        if (objSkill.Specialization != "")
                        {
                            objWriter.WriteElementString("spec", objSkill.Specialization);
                        }
                        objWriter.WriteElementString("category", objSkill.SkillCategory);
                        // </skill>
                        objWriter.WriteEndElement();
                    }
                }
                // </knowledgeskills>
                objWriter.WriteEndElement();
            }

            // Export Martial Arts.
            if (chkMartialArts.Checked)
            {
                // <martialarts>
                objWriter.WriteStartElement("martialarts");
                foreach (MartialArt objArt in _objCharacter.MartialArts)
                {
                    // <martialart>
                    objWriter.WriteStartElement("martialart");
                    objWriter.WriteElementString("name", objArt.Name);
                    objWriter.WriteElementString("rating", objArt.Rating.ToString());
                    if (objArt.Advantages.Count > 0)
                    {
                        // <advantages>
                        objWriter.WriteStartElement("advantages");
                        foreach (MartialArtAdvantage objAdvantage in objArt.Advantages)
                        {
                            objWriter.WriteElementString("advantage", objAdvantage.Name);
                        }
                        // </advantages>
                        objWriter.WriteEndElement();
                    }
                    // </martialart>
                    objWriter.WriteEndElement();
                }
                foreach (MartialArtManeuver objManeuver in _objCharacter.MartialArtManeuvers)
                {
                    objWriter.WriteElementString("maneuver", objManeuver.Name);
                }
                // </martialarts>
                objWriter.WriteEndElement();
            }

            // Export Spells.
            if (chkSpells.Checked)
            {
                // <spells>
                objWriter.WriteStartElement("spells");
                foreach (Spell objSpell in _objCharacter.Spells)
                {
                    objWriter.WriteStartElement("spell");
                    if (objSpell.Extra != "")
                    {
                        objWriter.WriteAttributeString("select", objSpell.Extra);
                    }
                    objWriter.WriteValue(objSpell.Name);
                    objWriter.WriteEndElement();
                }
                // </spells>
                objWriter.WriteEndElement();
            }

            // Export Complex Forms.
            if (chkComplexForms.Checked)
            {
                // <programs>
                objWriter.WriteStartElement("programs");
                foreach (TechProgram objProgram in _objCharacter.TechPrograms)
                {
                    // <program>
                    objWriter.WriteStartElement("program");
                    objWriter.WriteStartElement("name");
                    if (objProgram.Extra != "")
                    {
                        objWriter.WriteAttributeString("select", objProgram.Extra);
                    }
                    objWriter.WriteValue(objProgram.Name);
                    objWriter.WriteEndElement();
                    if (objProgram.Options.Count > 0)
                    {
                        // <options>
                        objWriter.WriteStartElement("options");
                        foreach (TechProgramOption objOption in objProgram.Options)
                        {
                            // <option>
                            objWriter.WriteStartElement("option");
                            objWriter.WriteStartElement("name");
                            if (objOption.Extra != "")
                            {
                                objWriter.WriteAttributeString("select", objOption.Extra);
                            }
                            objWriter.WriteValue(objOption.Name);
                            objWriter.WriteEndElement();
                            if (objOption.Rating > 0)
                            {
                                objWriter.WriteElementString("rating", objOption.Rating.ToString());
                            }
                            // </option>
                            objWriter.WriteEndElement();
                        }
                        // </options>
                        objWriter.WriteEndElement();
                    }
                    // </program>
                    objWriter.WriteEndElement();
                }
                // </programs>
                objWriter.WriteEndElement();
            }

            // Export Cyberware/Bioware.
            if (chkCyberware.Checked)
            {
                bool blnCyberware = false;
                bool blnBioware   = false;
                foreach (Cyberware objCharacterCyberware in _objCharacter.Cyberware)
                {
                    if (objCharacterCyberware.SourceType == Improvement.ImprovementSource.Bioware)
                    {
                        blnBioware = true;
                    }
                    if (objCharacterCyberware.SourceType == Improvement.ImprovementSource.Cyberware)
                    {
                        blnCyberware = true;
                    }
                    if (blnCyberware && blnBioware)
                    {
                        break;
                    }
                }

                if (blnCyberware)
                {
                    // <cyberwares>
                    objWriter.WriteStartElement("cyberwares");
                    foreach (Cyberware objCyberware in _objCharacter.Cyberware)
                    {
                        if (objCyberware.SourceType == Improvement.ImprovementSource.Cyberware)
                        {
                            // <cyberware>
                            objWriter.WriteStartElement("cyberware");
                            objWriter.WriteElementString("name", objCyberware.Name);
                            if (objCyberware.Rating > 0)
                            {
                                objWriter.WriteElementString("rating", objCyberware.Rating.ToString());
                            }
                            objWriter.WriteElementString("grade", objCyberware.Grade.ToString());
                            if (objCyberware.Cyberwares.Count > 0)
                            {
                                // <cyberwares>
                                objWriter.WriteStartElement("cyberwares");
                                foreach (Cyberware objChildCyberware in objCyberware.Cyberwares)
                                {
                                    if (objChildCyberware.Capacity != "[*]")
                                    {
                                        // <cyberware>
                                        objWriter.WriteStartElement("cyberware");
                                        objWriter.WriteElementString("name", objChildCyberware.Name);
                                        if (objChildCyberware.Rating > 0)
                                        {
                                            objWriter.WriteElementString("rating", objChildCyberware.Rating.ToString());
                                        }

                                        if (objChildCyberware.Gears.Count > 0)
                                        {
                                            WriteGear(objWriter, objChildCyberware.Gears);
                                        }
                                        // </cyberware>
                                        objWriter.WriteEndElement();
                                    }
                                }
                                // </cyberwares>
                                objWriter.WriteEndElement();
                            }

                            if (objCyberware.Gears.Count > 0)
                            {
                                WriteGear(objWriter, objCyberware.Gears);
                            }

                            // </cyberware>
                            objWriter.WriteEndElement();
                        }
                    }
                    // </cyberwares>
                    objWriter.WriteEndElement();
                }

                if (blnBioware)
                {
                    // <biowares>
                    objWriter.WriteStartElement("biowares");
                    foreach (Cyberware objCyberware in _objCharacter.Cyberware)
                    {
                        if (objCyberware.SourceType == Improvement.ImprovementSource.Bioware)
                        {
                            // <bioware>
                            objWriter.WriteStartElement("bioware");
                            objWriter.WriteElementString("name", objCyberware.Name);
                            if (objCyberware.Rating > 0)
                            {
                                objWriter.WriteElementString("rating", objCyberware.Rating.ToString());
                            }
                            objWriter.WriteElementString("grade", objCyberware.Grade.ToString());

                            if (objCyberware.Gears.Count > 0)
                            {
                                WriteGear(objWriter, objCyberware.Gears);
                            }
                            // </bioware>
                            objWriter.WriteEndElement();
                        }
                    }
                    // </biowares>
                    objWriter.WriteEndElement();
                }
            }

            // Export Lifestyle.
            if (chkLifestyle.Checked)
            {
                // <lifestyles>
                objWriter.WriteStartElement("lifestyles");
                foreach (Lifestyle objLifestyle in _objCharacter.Lifestyles)
                {
                    // <lifestyle>
                    objWriter.WriteStartElement("lifestyle");
                    objWriter.WriteElementString("name", objLifestyle.Name);
                    objWriter.WriteElementString("months", objLifestyle.Months.ToString());
                    if (objLifestyle.Comforts != "")
                    {
                        // This is an Advanced Lifestyle, so write out its properties.
                        objWriter.WriteElementString("cost", objLifestyle.Cost.ToString());
                        objWriter.WriteElementString("dice", objLifestyle.Dice.ToString());
                        objWriter.WriteElementString("multiplier", objLifestyle.Multiplier.ToString());
                        objWriter.WriteElementString("comforts", objLifestyle.Comforts);
                        objWriter.WriteElementString("entertainment", objLifestyle.Entertainment);
                        objWriter.WriteElementString("necessities", objLifestyle.Necessities);
                        objWriter.WriteElementString("neighborhood", objLifestyle.Neighborhood);
                        objWriter.WriteElementString("security", objLifestyle.Security);
                        if (objLifestyle.Qualities.Count > 0)
                        {
                            // <qualities>
                            objWriter.WriteStartElement("qualities");
                            foreach (string strQuality in objLifestyle.Qualities)
                            {
                                objWriter.WriteElementString("quality", strQuality);
                            }
                            // </qualities>
                            objWriter.WriteEndElement();
                        }
                    }
                    // </lifestyle>
                    objWriter.WriteEndElement();
                }
                // </lifestyles>
                objWriter.WriteEndElement();
            }

            // Export Armor.
            if (chkArmor.Checked)
            {
                // <armors>
                objWriter.WriteStartElement("armors");
                foreach (Armor objArmor in _objCharacter.Armor)
                {
                    // <armor>
                    objWriter.WriteStartElement("armor");
                    objWriter.WriteElementString("name", objArmor.Name);
                    if (objArmor.ArmorMods.Count > 0)
                    {
                        // <mods>
                        objWriter.WriteStartElement("mods");
                        foreach (ArmorMod objMod in objArmor.ArmorMods)
                        {
                            // <mod>
                            objWriter.WriteStartElement("mod");
                            objWriter.WriteElementString("name", objMod.Name);
                            if (objMod.Rating > 0)
                            {
                                objWriter.WriteElementString("rating", objMod.Rating.ToString());
                            }
                            // </mod>
                            objWriter.WriteEndElement();
                        }
                        // </mods>
                        objWriter.WriteEndElement();
                    }

                    if (objArmor.Gears.Count > 0)
                    {
                        WriteGear(objWriter, objArmor.Gears);
                    }

                    // </armor>
                    objWriter.WriteEndElement();
                }
                // </armors>
                objWriter.WriteEndElement();
            }

            // Export Weapons.
            if (chkWeapons.Checked)
            {
                // <weapons>
                objWriter.WriteStartElement("weapons");
                foreach (Weapon objWeapon in _objCharacter.Weapons)
                {
                    // Don't attempt to export Cyberware and Gear Weapons since those are handled by those object types. The default Unarmed Attack Weapon should also not be exported.
                    if (objWeapon.Category != "Cyberware" && objWeapon.Category != "Gear" && objWeapon.ExternalId != Constants.UnarmedAttack)
                    {
                        // <weapon>
                        objWriter.WriteStartElement("weapon");
                        objWriter.WriteElementString("name", objWeapon.Name);

                        // Weapon Accessories.
                        if (objWeapon.WeaponAccessories.Count > 0)
                        {
                            // <accessories>
                            objWriter.WriteStartElement("accessories");
                            foreach (WeaponAccessory objAccessory in objWeapon.WeaponAccessories)
                            {
                                // Don't attempt to export items included in the Weapon.
                                if (!objAccessory.IncludedInParent)
                                {
                                    // <accessory>
                                    objWriter.WriteStartElement("accessory");
                                    objWriter.WriteElementString("name", objAccessory.Name);
                                    objWriter.WriteElementString("mount", objAccessory.Mount);

                                    if (objAccessory.Gears.Count > 0)
                                    {
                                        WriteGear(objWriter, objAccessory.Gears);
                                    }

                                    // </accessory>
                                    objWriter.WriteEndElement();
                                }
                            }
                            // </accessories>
                            objWriter.WriteEndElement();
                        }

                        // Weapon Mods.
                        if (objWeapon.WeaponMods.Count > 0)
                        {
                            // <mods>
                            objWriter.WriteStartElement("mods");
                            foreach (WeaponMod objMod in objWeapon.WeaponMods)
                            {
                                // Don't attempt to export items included in the Weapon.
                                if (!objMod.IncludedInParent)
                                {
                                    // <mod>
                                    objWriter.WriteStartElement("mod");
                                    objWriter.WriteElementString("name", objMod.Name);
                                    // </mod>
                                    objWriter.WriteEndElement();
                                }
                            }
                            // </mods>
                            objWriter.WriteEndElement();
                        }

                        // Underbarrel Weapon.
                        if (objWeapon.Weapons.Count > 0)
                        {
                            foreach (Weapon objUnderbarrelWeapon in objWeapon.Weapons)
                            {
                                if (!objUnderbarrelWeapon.IncludedInParent)
                                {
                                    objWriter.WriteElementString("underbarrel", objUnderbarrelWeapon.Name);
                                }
                            }
                        }

                        // </weapon>
                        objWriter.WriteEndElement();
                    }
                }
                // </weapons>
                objWriter.WriteEndElement();
            }

            // Export Gear.
            if (chkGear.Checked)
            {
                WriteGear(objWriter, _objCharacter.Gear);
            }

            // Export Vehicles.
            if (chkVehicles.Checked)
            {
                // <vehicles>
                objWriter.WriteStartElement("vehicles");
                foreach (Vehicle objVehicle in _objCharacter.Vehicles)
                {
                    bool blnWeapons = false;
                    // <vehicle>
                    objWriter.WriteStartElement("vehicle");
                    objWriter.WriteElementString("name", objVehicle.Name);
                    if (objVehicle.VehicleMods.Count > 0)
                    {
                        // <mods>
                        objWriter.WriteStartElement("mods");
                        foreach (VehicleMod objVehicleMod in objVehicle.VehicleMods)
                        {
                            // Only write out the Mods that are not part of the base vehicle.
                            if (!objVehicleMod.IncludedInParent)
                            {
                                // <mod>
                                objWriter.WriteStartElement("mod");
                                objWriter.WriteElementString("name", objVehicleMod.Name);
                                if (objVehicleMod.Rating > 0)
                                {
                                    objWriter.WriteElementString("rating", objVehicleMod.Rating.ToString());
                                }
                                // </mod>
                                objWriter.WriteEndElement();

                                // See if this is a Weapon Mount with Weapons.
                                if (objVehicleMod.Weapons.Count > 0)
                                {
                                    blnWeapons = true;
                                }
                            }
                            else
                            {
                                // See if this is a Weapon Mount with Weapons.
                                if (objVehicleMod.Weapons.Count > 0)
                                {
                                    blnWeapons = true;
                                }
                            }
                        }
                        // </mods>
                        objWriter.WriteEndElement();
                    }

                    // If there are Weapons, add them.
                    if (blnWeapons)
                    {
                        // <weapons>
                        objWriter.WriteStartElement("weapons");
                        foreach (VehicleMod objVehicleMod in objVehicle.VehicleMods)
                        {
                            foreach (Weapon objWeapon in objVehicleMod.Weapons)
                            {
                                // <weapon>
                                objWriter.WriteStartElement("weapon");
                                objWriter.WriteElementString("name", objWeapon.Name);

                                // Weapon Accessories.
                                if (objWeapon.WeaponAccessories.Count > 0)
                                {
                                    // <accessories>
                                    objWriter.WriteStartElement("accessories");
                                    foreach (WeaponAccessory objAccessory in objWeapon.WeaponAccessories)
                                    {
                                        // Don't attempt to export items included in the Weapon.
                                        if (!objAccessory.IncludedInParent)
                                        {
                                            // <accessory>
                                            objWriter.WriteStartElement("accessory");
                                            objWriter.WriteElementString("name", objAccessory.Name);
                                            objWriter.WriteElementString("mount", objAccessory.Mount);
                                            // </accessory>
                                            objWriter.WriteEndElement();
                                        }
                                    }
                                    // </accessories>
                                    objWriter.WriteEndElement();
                                }

                                // Weapon Mods.
                                if (objWeapon.WeaponMods.Count > 0)
                                {
                                    // <mods>
                                    objWriter.WriteStartElement("mods");
                                    foreach (WeaponMod objMod in objWeapon.WeaponMods)
                                    {
                                        // Don't attempt to export items included in the Weapon.
                                        if (!objMod.IncludedInParent)
                                        {
                                            // <mod>
                                            objWriter.WriteStartElement("mod");
                                            objWriter.WriteElementString("name", objMod.Name);
                                            // </mod>
                                            objWriter.WriteEndElement();
                                        }
                                    }
                                    // </mods>
                                    objWriter.WriteEndElement();
                                }

                                // Underbarrel Weapon.
                                if (objWeapon.Weapons.Count > 0)
                                {
                                    foreach (Weapon objUnderbarrelWeapon in objWeapon.Weapons)
                                    {
                                        objWriter.WriteElementString("underbarrel", objUnderbarrelWeapon.Name);
                                    }
                                }

                                // </weapon>
                                objWriter.WriteEndElement();
                            }
                        }
                        // </weapons>
                        objWriter.WriteEndElement();
                    }

                    // Gear.
                    if (objVehicle.Gears.Count > 0)
                    {
                        WriteGear(objWriter, objVehicle.Gears);
                    }
                    // </vehicle>
                    objWriter.WriteEndElement();
                }
                // </vehicles>
                objWriter.WriteEndElement();
            }

            // </pack>
            objWriter.WriteEndElement();
            // </packs>
            objWriter.WriteEndElement();
            // </chummer>
            objWriter.WriteEndElement();

            objWriter.WriteEndDocument();
            objWriter.Close();
            objStream.Close();

            MessageBox.Show(LanguageManager.Instance.GetString("Message_CreatePACKSKit_SuiteCreated").Replace("{0}", txtName.Text), LanguageManager.Instance.GetString("MessageTitle_CreatePACKSKit_SuiteCreated"), MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.DialogResult = DialogResult.OK;
        }
示例#21
0
        /// <summary>
        /// A file is done downloading, so increment the overall progress bar and check to see if all downloads are done.
        /// </summary>
        private void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            // Detach the event handlers once they're done so they don't continue to fire and/or consume memory.
            WebClient wc = new WebClient();

            wc = (WebClient)sender;
            wc.DownloadProgressChanged -= wc_DownloadProgressChanged;
            wc.DownloadFileCompleted   -= wc_DownloadFileCompleted;

            _intDoneCount++;
            pgbOverallProgress.Value++;
            if (_intDoneCount == _intFileCount)
            {
                bool blnUnzipSuccess = true;

                // Unzip the data files that have been downloaded.
                OmaeHelper objHelper = new OmaeHelper();
                foreach (string strFile in Directory.GetFiles(Path.Combine(GlobalOptions.ApplicationPath(), "data"), "*.zip"))
                {
                    try
                    {
                        byte[] bytFile = File.ReadAllBytes(strFile);
                        bytFile = objHelper.Decompress(bytFile);
                        File.WriteAllBytes(strFile.Replace(".zip", ".xml"), bytFile);
                        if (!strFile.Contains("\\Debug\\"))
                        {
                            File.Delete(strFile);
                        }
                    }
                    catch
                    {
                        blnUnzipSuccess = false;
                    }
                }

                if (!_blnSilentMode)
                {
                    // If the update process is not running in silent mode, display a message informing the user that the update is done.
                    pgbOverallProgress.Visible = false;
                    pgbFileProgress.Visible    = false;
                    lblDone.Visible            = true;
                }

                if (ValidateFiles() && blnUnzipSuccess)
                {
                    if (_blnExeDownloaded)
                    {
                        cmdRestart.Visible = true;
                        if (_blnSilentMode)
                        {
                            // The user is in silent mode, so restart the application.
                            Application.Restart();
                        }
                    }

                    // Close the window when we're done in Silent Mode.
                    if (_blnSilentMode)
                    {
                        this.Close();
                    }
                }
                else
                {
                    // Show the progress bars again.
                    pgbOverallProgress.Visible = true;
                    pgbFileProgress.Visible    = true;
                    lblDone.Visible            = false;

                    // Something did not download properly.
                    if (_blnSilentMode)
                    {
                        FetchXML();
                    }
                    else
                    {
                        // Make a list of each item that is currently checked.
                        List <string> lstStrings = new List <string>();

                        // Loop through all of the root-level nodes in the update tree.
                        foreach (TreeNode nodRoot in treeUpdate.Nodes)
                        {
                            // Loop through each of the child nodes.
                            foreach (TreeNode nodNode in nodRoot.Nodes)
                            {
                                if (nodNode.Checked)
                                {
                                    lstStrings.Add(nodNode.Tag.ToString());
                                }
                            }
                        }

                        FetchXML();

                        // Select all of the items that were selected before.
                        // Loop through all of the root-level nodes in the update tree.
                        foreach (string strString in lstStrings)
                        {
                            foreach (TreeNode nodRoot in treeUpdate.Nodes)
                            {
                                // Loop through each of the child nodes.
                                foreach (TreeNode nodNode in nodRoot.Nodes)
                                {
                                    if (nodNode.Tag.ToString() == strString)
                                    {
                                        nodNode.Checked = true;
                                    }
                                }
                            }
                        }

                        // Click the button to do it all again.
                        cmdUpdate_Click(null, null);
                    }
                }
            }
        }
示例#22
0
        /// <summary>
        /// Download the selected updates and overwrite the existing files.
        /// </summary>
        private void DownloadUpdates()
        {
            cmdUpdate.Enabled    = false;
            cmdSelectAll.Enabled = false;

            // Determine the temporary location for the new executable if it is downloaded.
            string strNewPath  = Path.Combine(Path.GetTempPath(), "chummer.exe");
            string strFilePath = GlobalOptions.ApplicationPath() + Path.DirectorySeparatorChar;

            WebClient wc = new WebClient();

            // Count all of the nodes that have been selected to determine the progress bar's max value.
            pgbOverallProgress.Value   = 0;
            pgbOverallProgress.Minimum = 0;
            pgbOverallProgress.Maximum = 0;
            foreach (TreeNode nodRoot in treeUpdate.Nodes)
            {
                foreach (TreeNode nodNode in nodRoot.Nodes)
                {
                    if (nodNode.Checked)
                    {
                        pgbOverallProgress.Maximum++;
                        _intFileCount++;
                    }
                }
            }

            if (_blnSilentMode)
            {
                // If nothing is selected (Language files that the user does not have installed), close the window.
                if (pgbOverallProgress.Maximum == 0)
                {
                    this.Close();
                    return;
                }

                this.Opacity = 100;
                this.Show();
            }

            // Loop through all of the root-level nodes in the update tree.
            foreach (TreeNode nodRoot in treeUpdate.Nodes)
            {
                // Loop through each of the child nodes.
                foreach (TreeNode nodNode in nodRoot.Nodes)
                {
                    if (nodNode.Checked)
                    {
                        // If an item has been checked, download it.
                        wc = new WebClient();
                        pgbFileProgress.Value       = 0;
                        wc.DownloadProgressChanged += wc_DownloadProgressChanged;

                        if (nodNode.Tag.ToString().Contains(".xml") || nodNode.Tag.ToString().Contains(".xsl"))
                        {
                            // Make sure the target directory exists. If it doesn't, create it.
                            string[]      strCheckDirectory = (strFilePath + nodNode.Tag.ToString().Replace('/', Path.DirectorySeparatorChar)).Split(Path.DirectorySeparatorChar);
                            StringBuilder strDirectory      = new StringBuilder();
                            for (int i = 0; i < strCheckDirectory.Length - 1; i++)
                            {
                                strDirectory.Append(strCheckDirectory[i]).Append(Path.DirectorySeparatorChar);
                            }
                            if (!Directory.Exists(strDirectory.ToString()))
                            {
                                Directory.CreateDirectory(strDirectory.ToString());
                            }

                            // Downloading an XML or XSL file.
                            wc.Encoding = Encoding.UTF8;
                            wc.DownloadFileCompleted += wc_DownloadFileCompleted;
                            if (nodNode.Tag.ToString().Contains("lang/"))
                            {
                                wc.DownloadFileAsync(new Uri("http://www.chummergen.com/dev/chummersr5/" + nodNode.Tag.ToString()), strFilePath + nodNode.Tag.ToString().Replace('/', Path.DirectorySeparatorChar));
                            }
                            else
                            {
                                wc.DownloadFileAsync(new Uri("http://www.chummergen.com/dev/chummersr5/" + nodNode.Tag.ToString().Replace(".xml", ".zip")), strFilePath + nodNode.Tag.ToString().Replace('/', Path.DirectorySeparatorChar).Replace(".xml", ".zip"));
                            }
                        }
                        else
                        {
                            if (nodNode.Tag.ToString().Contains(".exe"))
                            {
                                // Download the appliation changelog.
                                try
                                {
                                    wc.Encoding = Encoding.UTF8;
                                    wc.DownloadFile("http://www.chummergen.com/dev/chummersr5/changelog.txt", Path.Combine(GlobalOptions.ApplicationPath(), "changelog.txt"));
                                    webNotes.DocumentText = "<font size=\"-1\" face=\"Courier New,Serif\">" + File.ReadAllText(Path.Combine(GlobalOptions.ApplicationPath(), "changelog.txt")).Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\n", "<br />") + "</font>";
                                }
                                catch
                                {
                                    // Not a critical file, so don't freak out if it can't be downloaded.
                                }

                                // Downloading the application executable file.
                                try
                                {
                                    wc.Encoding = Encoding.Default;
                                    wc.DownloadFileCompleted += wc_DownloadExeFileCompleted;
                                    wc.DownloadFileCompleted += wc_DownloadFileCompleted;
                                    wc.DownloadFileAsync(new Uri("http://www.chummergen.com/dev/chummersr5/" + nodNode.Tag), strNewPath);
                                }
                                catch
                                {
                                    // The executable couldn't be downloaded, so don't try to replace the current app with something that doesn't exist.
                                }
                            }
                        }
                        Application.DoEvents();
                    }
                }
            }
        }
示例#23
0
        /// <summary>
        /// Retrieve the manifestdata.xml file and determine if any updates are available.
        /// </summary>
        private void FetchXML()
        {
            treeUpdate.Nodes.Clear();

            XmlDocument objXmlDocument     = new XmlDocument();
            XmlDocument objXmlFileDocument = new XmlDocument();
            XmlNode     objXmlFileNode;
            string      strLastType = "";

            XmlDocument objXmlLanguageDocument = new XmlDocument();

            // Download the manifestdata.xml file which describes all of the files available for download and extract its nodes.
            // Timeout set to 30 seconds.
            HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create("http://www.chummergen.com/dev/chummersr5/manifestdata.xml");

            //HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create("http://localhost/manifestdata.xml");
            objRequest.Timeout = 30000;
            HttpWebResponse objResponse;
            StreamReader    objReader;

            // Exceptions happen when the request times out or the file is not found. In either case, display a message saying the update
            // information is temporarily unavailable.
            try
            {
                objResponse = (HttpWebResponse)objRequest.GetResponse();
                objReader   = new StreamReader(objResponse.GetResponseStream());
            }
            catch
            {
                // Don't show the error message if we're running in silent mode.
                if (!_blnSilentMode)
                {
                    MessageBox.Show(LanguageManager.Instance.GetString("Message_Update_CannotConnect"), LanguageManager.Instance.GetString("Title_Update"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                this.Close();
                return;
            }

            // Load the downloaded manifestdata.xml file.
            objXmlDocument.Load(objReader);

            // Download the manifestlang.xml file which describes the language content available for download.
            objRequest = (HttpWebRequest)WebRequest.Create("http://www.chummergen.com/dev/chummersr5/manifestlang.xml");
            // objRequest = (HttpWebRequest)WebRequest.Create("http://localhost/manifestlang.xml");
            try
            {
                objResponse = (HttpWebResponse)objRequest.GetResponse();
                objReader   = new StreamReader(objResponse.GetResponseStream());
            }
            catch
            {
                // Don't show the error message if we're running in silent mode.
                if (!_blnSilentMode)
                {
                    MessageBox.Show(LanguageManager.Instance.GetString("Message_Update_CannotConnect"), LanguageManager.Instance.GetString("Title_Update"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                this.Close();
                return;
            }

            // Merge the manifests together into a single usable XmlDocument.
            objXmlLanguageDocument.Load(objReader);
            XmlNodeList objXmlList = objXmlLanguageDocument.SelectNodes("/manifest/*");

            foreach (XmlNode objNode in objXmlList)
            {
                XmlNode objImported = objXmlDocument.ImportNode(objNode, true);
                objXmlDocument.DocumentElement.AppendChild(objImported);
            }

            XmlNodeList objXmlNodeList = objXmlDocument.SelectNodes("/manifest/file");

            TreeNode nodRoot = new TreeNode();

            foreach (XmlNode objXmlNode in objXmlNodeList)
            {
                // A new type has been found, so attach the current root node to the tree and start a new one.
                if (objXmlNode["type"].InnerText != strLastType)
                {
                    if (strLastType != "")
                    {
                        nodRoot.ExpandAll();
                        if (nodRoot.GetNodeCount(false) > 0)
                        {
                            treeUpdate.Nodes.Add(nodRoot);
                        }
                        nodRoot = new TreeNode();
                    }
                    nodRoot.Text = objXmlNode["type"].InnerText;
                    strLastType  = objXmlNode["type"].InnerText;
                }

                // If we're on the EXE file, check the version numbers.
                bool blnCreateNode = true;
                if (objXmlNode["name"].InnerText.Contains(".exe"))
                {
                    if (Convert.ToInt32(objXmlNode["version"].InnerText.Replace(".", string.Empty)) > Convert.ToInt32(Application.ProductVersion.Replace(".", string.Empty)))
                    {
                        blnCreateNode = true;
                    }
                    else
                    {
                        blnCreateNode = false;
                    }
                }

                // If we're on an XML file, check for the existing file and compare version numbers.
                if (objXmlNode["name"].InnerText.Contains(".xml"))
                {
                    try
                    {
                        objXmlFileDocument.Load(GlobalOptions.ApplicationPath() + Path.DirectorySeparatorChar + objXmlNode["name"].InnerText.Replace('/', Path.DirectorySeparatorChar));
                        objXmlFileNode = objXmlFileDocument.SelectSingleNode("/chummer/version");
                        if (Convert.ToInt32(objXmlNode["version"].InnerText) > Convert.ToInt32(objXmlFileNode.InnerText))
                        {
                            blnCreateNode = true;
                        }
                        else
                        {
                            blnCreateNode = false;
                        }
                    }
                    catch
                    {
                        blnCreateNode = true;
                    }

                    // Check for localisation limitations.
                    if (GlobalOptions.Instance.LocalisedUpdatesOnly)
                    {
                        // Only check if we're looking at a non-en-us language file.
                        if (objXmlNode["name"].InnerText.StartsWith("lang") && !objXmlNode["name"].InnerText.Contains("en-us"))
                        {
                            if (!objXmlNode["name"].InnerText.EndsWith(GlobalOptions.Instance.Language.Substring(0, 2) + ".xml") && !objXmlNode["name"].InnerText.EndsWith(GlobalOptions.Instance.Language.Substring(0, 2) + "_data.xml"))
                            {
                                blnCreateNode = false;
                            }
                        }
                    }
                }

                // If we're on an XSL file, check for the existing file and compare version numbers.
                if (objXmlNode["name"].InnerText.Contains(".xsl"))
                {
                    try
                    {
                        StreamReader objFile = new StreamReader(GlobalOptions.ApplicationPath() + Path.DirectorySeparatorChar + objXmlNode["name"].InnerText.Replace('/', Path.DirectorySeparatorChar));
                        string       strLine = "";
                        while ((strLine = objFile.ReadLine()) != null)
                        {
                            if (strLine.Contains("<!-- Version"))
                            {
                                int intVersion = Convert.ToInt32(strLine.Replace("<!-- Version ", string.Empty).Replace(" -->", string.Empty));
                                if (intVersion < Convert.ToInt32(objXmlNode["version"].InnerText))
                                {
                                    blnCreateNode = true;
                                }
                                else
                                {
                                    blnCreateNode = false;
                                }
                                break;
                            }
                        }
                        objFile.Close();
                    }
                    catch (Exception)
                    {
                        blnCreateNode = true;
                    }

                    // Check for localisation limitations.
                    if (GlobalOptions.Instance.LocalisedUpdatesOnly)
                    {
                        // Only check if we're looking at a non-en-us sheet file.
                        string[] strSplit = objXmlNode["name"].InnerText.Split('/');
                        if (strSplit.Length > 2)
                        {
                            if (!objXmlNode["name"].InnerText.Contains("/" + GlobalOptions.Instance.Language.Substring(0, 2) + "/"))
                            {
                                blnCreateNode = false;
                            }
                        }
                    }
                }

                if (blnCreateNode)
                {
                    TreeNode nodNode = new TreeNode();
                    nodNode.Text        = objXmlNode["description"].InnerText;
                    nodNode.Tag         = objXmlNode["name"].InnerText;
                    nodNode.ToolTipText = objXmlNode["notes"].InnerText;
                    if (_blnSilentMode)
                    {
                        if (!objXmlNode["name"].InnerText.Contains("lang/"))
                        {
                            // Automatically select any file that is not a language file.
                            nodNode.Checked = true;
                        }
                        else
                        {
                            bool blnChecked = false;
                            // Automatically select the default English file.
                            if (objXmlNode["name"].InnerText == "lang/en-us.xml")
                            {
                                blnChecked = true;
                            }
                            else
                            {
                                // If this is a non-English language file, only select it if the user already has it installed.
                                string strLangPath = Path.Combine(GlobalOptions.ApplicationPath(), objXmlNode["name"].InnerText.Replace('/', Path.DirectorySeparatorChar));
                                if (File.Exists(strLangPath))
                                {
                                    blnChecked = true;
                                }
                            }
                            nodNode.Checked = blnChecked;
                        }
                    }
                    nodRoot.Nodes.Add(nodNode);
                }
            }

            objReader.Close();

            // Attach the last root node to the tree.
            nodRoot.ExpandAll();
            if (nodRoot.GetNodeCount(false) > 0)
            {
                treeUpdate.Nodes.Add(nodRoot);
            }

            if (treeUpdate.GetNodeCount(false) == 0)
            {
                this.Visible = false;
                if (!_blnSilentMode)
                {
                    MessageBox.Show(LanguageManager.Instance.GetString("Message_Update_NoNewUpdates"), LanguageManager.Instance.GetString("Title_Update"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                this.Close();
            }
            else
            if (_blnSilentMode)
            {
                DownloadUpdates();
            }
            else
            {
                this.Opacity = 100;
                this.Show();
            }

            // Close the connection now that we're done with it.
            objResponse.Close();
        }
示例#24
0
        /// <summary>
        /// Create a new character and show the Create Form.
        /// </summary>
        private void ShowNewForm(object sender, EventArgs e)
        {
            Character objCharacter = new Character();

            if (Directory.GetFiles(Path.Combine(GlobalOptions.ApplicationPath(), "settings"), "*.xml").Count() > 1)
            {
                frmSelectSetting frmPickSetting = new frmSelectSetting();
                frmPickSetting.ShowDialog(this);

                if (frmPickSetting.DialogResult == DialogResult.Cancel)
                {
                    return;
                }

                objCharacter.SettingsFile = frmPickSetting.SettingsFile;
            }
            else
            {
                string strSettingsFile = Directory.GetFiles(Path.Combine(GlobalOptions.ApplicationPath(), "settings"), "*.xml")[0];
                strSettingsFile           = strSettingsFile.Replace(Path.Combine(GlobalOptions.ApplicationPath(), "settings"), string.Empty);
                strSettingsFile           = strSettingsFile.Replace(Path.DirectorySeparatorChar, ' ').Trim();
                objCharacter.SettingsFile = strSettingsFile;
            }

            // Show the BP selection window.
            frmSelectBP frmBP = new frmSelectBP(objCharacter);

            frmBP.ShowDialog();

            if (frmBP.DialogResult == DialogResult.Cancel)
            {
                return;
            }

            if (objCharacter.BuildMethod != CharacterBuildMethod.Priority)
            {
                // Show the Metatype selection window.
                frmMetatype frmSelectMetatype = new frmMetatype(objCharacter);
                frmSelectMetatype.ShowDialog();

                if (frmSelectMetatype.DialogResult == DialogResult.Cancel)
                {
                    return;
                }
            }
            else
            {
                //Show the Priority selection window.
                frmPriority frmSelectPriority = new frmPriority(objCharacter);
                frmSelectPriority.ShowDialog();

                if (frmSelectPriority.DialogResult == DialogResult.Cancel)
                {
                    return;
                }
            }

            // Add the Unarmed Attack Weapon to the character.
            try
            {
                XmlDocument objXmlDocument = XmlManager.Instance.Load("weapons.xml");
                XmlNode     objXmlWeapon   = objXmlDocument.SelectSingleNode("/chummer/weapons/weapon[id = \"" + Constants.UnarmedAttack + "\"]");
                TreeNode    objDummy       = new TreeNode();
                Weapon      objWeapon      = new Weapon(objCharacter);
                objWeapon.Create(objXmlWeapon, objCharacter, objDummy, null, null, null);
                objCharacter.Weapons.Add(objWeapon);
            }
            catch
            {
            }

            frmCreate frmNewCharacter = new frmCreate(objCharacter);

            frmNewCharacter.MdiParent   = this;
            frmNewCharacter.WindowState = FormWindowState.Maximized;
            frmNewCharacter.Show();

            objCharacter.CharacterNameChanged += objCharacter_CharacterNameChanged;
        }
示例#25
0
        private void objRecord_OmaeDownloadClicked(Object sender)
        {
            // Setup the web service.
            OmaeRecord     objRecord  = (OmaeRecord)sender;
            omaeSoapClient objService = _objOmaeHelper.GetOmaeService();

            if (_objMode == OmaeMode.Character)
            {
                if (objRecord.CharacterType != 4)
                {
                    // Download the selected character.
                    string strFileName = objRecord.CharacterName + ".chum";
                    strFileName = FileSafe(strFileName);

                    // If the Omae save directory does not yet exist, create it.
                    string strSavePath = Path.Combine(GlobalOptions.ApplicationPath(), "saves");
                    if (!Directory.Exists(strSavePath))
                    {
                        Directory.CreateDirectory(strSavePath);
                    }
                    if (!Directory.Exists(Path.Combine(strSavePath, "omae")))
                    {
                        Directory.CreateDirectory(Path.Combine(strSavePath, "omae"));
                    }

                    // See if there is already a file with the character's name in the Downloads directory.
                    string strFullPath = Path.Combine(strSavePath, "omae");
                    strFullPath = Path.Combine(strFullPath, strFileName);
                    if (File.Exists(strFullPath))
                    {
                        if (MessageBox.Show(LanguageManager.Instance.GetString("Message_Omae_FileExists").Replace("{0}", strFileName), LanguageManager.Instance.GetString("MessageTitle_Omae_FileExists"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                        {
                            return;
                        }
                    }

                    try
                    {
                        // Download the compressed file.
                        byte[] bytFile = objService.DownloadCharacter(objRecord.CharacterID);

                        if (bytFile.Length == 0)
                        {
                            MessageBox.Show(LanguageManager.Instance.GetString("Message_Omae_CannotFindCharacter"), LanguageManager.Instance.GetString("MessageTitle_Omae_CannotFindCharacter"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                            objService.Close();
                            return;
                        }

                        // Decompress the byte array and write it to a file.
                        bytFile = _objOmaeHelper.Decompress(bytFile);
                        string strWritePath = Path.Combine(strSavePath, "omae");
                        strWritePath = Path.Combine(strWritePath, strFileName);
                        File.WriteAllBytes(strWritePath, bytFile);
                        if (MessageBox.Show(LanguageManager.Instance.GetString("Message_Omae_CharacterDownloaded"), LanguageManager.Instance.GetString("MessageTitle_Omae_CharacterDownloaded"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            _frmMain.LoadCharacter(strWritePath);
                        }
                    }
                    catch (EndpointNotFoundException)
                    {
                        MessageBox.Show(NO_CONNECTION_MESSAGE, NO_CONNECTION_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    // Download the selected NPC pack.
                    string strFileName = objRecord.CharacterName + ".chum";
                    strFileName = FileSafe(strFileName);

                    // If the Omae save directory does not yet exist, create it.
                    string strSavePath = Path.Combine(GlobalOptions.ApplicationPath(), "saves");
                    if (!Directory.Exists(strSavePath))
                    {
                        Directory.CreateDirectory(strSavePath);
                    }

                    try
                    {
                        // Download the compressed file.
                        byte[] bytFile = objService.DownloadCharacter(objRecord.CharacterID);

                        if (bytFile.Length == 0)
                        {
                            MessageBox.Show(LanguageManager.Instance.GetString("Message_Omae_CannotFindCharacter"), LanguageManager.Instance.GetString("MessageTitle_Omae_CannotFindCharacter"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                            objService.Close();
                            return;
                        }

                        // Decompress the byte array and write it to a file.
                        _objOmaeHelper.DecompressNPCs(bytFile);
                        MessageBox.Show(LanguageManager.Instance.GetString("Message_Omae_NPCPackDownloaded"), LanguageManager.Instance.GetString("MessageTitle_Omae_CharacterDownloaded"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (EndpointNotFoundException)
                    {
                        MessageBox.Show(NO_CONNECTION_MESSAGE, NO_CONNECTION_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else if (_objMode == OmaeMode.Data)
            {
                try
                {
                    // Download the compressed file.
                    byte[] bytFile = objService.DownloadDataFile(objRecord.CharacterID);

                    if (bytFile.Length == 0)
                    {
                        MessageBox.Show(LanguageManager.Instance.GetString("Message_Omae_CannotFindData"), LanguageManager.Instance.GetString("MessageTitle_Omae_CannotFindData"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                        objService.Close();
                        return;
                    }

                    // Decompress the byte array and write it to a file.
                    _objOmaeHelper.DecompressDataFile(bytFile, objRecord.CharacterID.ToString());
                    // Show a message saying everything is done.
                    MessageBox.Show(LanguageManager.Instance.GetString("Message_Omae_DataDownloaded"), LanguageManager.Instance.GetString("MessageTitle_Omae_DataDownloaded"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (EndpointNotFoundException)
                {
                    MessageBox.Show(NO_CONNECTION_MESSAGE, NO_CONNECTION_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else if (_objMode == OmaeMode.Sheets)
            {
                // If the Omae sheets directory does not yet exist, create it.
                string strSheetsPath = Path.Combine(GlobalOptions.ApplicationPath(), "sheets");
                if (!Directory.Exists(Path.Combine(strSheetsPath, "omae")))
                {
                    Directory.CreateDirectory(Path.Combine(strSheetsPath, "omae"));
                }

                try
                {
                    // Download the compressed file.
                    byte[] bytFile = objService.DownloadSheet(objRecord.CharacterID);

                    if (bytFile.Length == 0)
                    {
                        MessageBox.Show(LanguageManager.Instance.GetString("Message_Omae_CannotFindSheet"), LanguageManager.Instance.GetString("MessageTitle_Omae_CannotFindSheet"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                        objService.Close();
                        return;
                    }

                    // Decompress the byte array and write it to a file.
                    _objOmaeHelper.DecompressCharacterSheet(bytFile);
                    // Show a message saying everything is done.
                    MessageBox.Show(LanguageManager.Instance.GetString("Message_Omae_SheetDownloaded"), LanguageManager.Instance.GetString("MessageTitle_Omae_SheetDownloaded"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (EndpointNotFoundException)
                {
                    MessageBox.Show(NO_CONNECTION_MESSAGE, NO_CONNECTION_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            // Close the service now that we're done with it.
            objService.Close();
        }
示例#26
0
        private void frmViewer_Load(object sender, EventArgs e)
        {
            _blnLoading = true;
            List <ListItem> lstFiles = new List <ListItem>();

            // Populate the XSLT list with all of the XSL files found in the sheets directory.
            foreach (string strFile in Directory.GetFiles(GlobalOptions.ApplicationPath() + Path.DirectorySeparatorChar + "sheets"))
            {
                // Only show files that end in .xsl. Do not include files that end in .xslt since they are used as "hidden" reference sheets (hidden because they are partial templates that cannot be used on their own).
                if (!strFile.EndsWith(".xslt") && strFile.EndsWith(".xsl"))
                {
                    string   strFileName = strFile.Replace(GlobalOptions.ApplicationPath() + Path.DirectorySeparatorChar + "sheets" + Path.DirectorySeparatorChar, string.Empty).Replace(".xsl", string.Empty);
                    ListItem objItem     = new ListItem();
                    objItem.Value = strFileName;
                    objItem.Name  = strFileName;
                    lstFiles.Add(objItem);

                    //cboXSLT.Items.Add(strFileName);
                }
            }

            try
            {
                // Populate the XSL list with all of the XSL files found in the sheets\[language] directory.
                if (GlobalOptions.Instance.Language != "en-us")
                {
                    XmlDocument objLanguageDocument = LanguageManager.Instance.XmlDoc;
                    string      strLanguage         = objLanguageDocument.SelectSingleNode("/chummer/name").InnerText;

                    foreach (string strFile in Directory.GetFiles(GlobalOptions.ApplicationPath() + Path.DirectorySeparatorChar + "sheets" + Path.DirectorySeparatorChar + GlobalOptions.Instance.Language))
                    {
                        // Only show files that end in .xsl. Do not include files that end in .xslt since they are used as "hidden" reference sheets (hidden because they are partial templates that cannot be used on their own).
                        if (!strFile.EndsWith(".xslt") && strFile.EndsWith(".xsl"))
                        {
                            string   strFileName = strFile.Replace(GlobalOptions.ApplicationPath() + Path.DirectorySeparatorChar + "sheets" + Path.DirectorySeparatorChar + GlobalOptions.Instance.Language + Path.DirectorySeparatorChar, string.Empty).Replace(".xsl", string.Empty);
                            ListItem objItem     = new ListItem();
                            objItem.Value = GlobalOptions.Instance.Language + Path.DirectorySeparatorChar + strFileName;
                            objItem.Name  = strLanguage + ": " + strFileName;
                            lstFiles.Add(objItem);
                        }
                    }
                }
            }
            catch
            {
            }

            try
            {
                // Populate the XSLT list with all of the XSL files found in the sheets\omae directory.
                foreach (string strFile in Directory.GetFiles(GlobalOptions.ApplicationPath() + Path.DirectorySeparatorChar + "sheets" + Path.DirectorySeparatorChar + "omae"))
                {
                    // Only show files that end in .xsl. Do not include files that end in .xslt since they are used as "hidden" reference sheets (hidden because they are partial templates that cannot be used on their own).
                    if (!strFile.EndsWith(".xslt") && strFile.EndsWith(".xsl"))
                    {
                        string   strFileName = strFile.Replace(GlobalOptions.ApplicationPath() + Path.DirectorySeparatorChar + "sheets" + Path.DirectorySeparatorChar + "omae" + Path.DirectorySeparatorChar, string.Empty).Replace(".xsl", string.Empty);
                        ListItem objItem     = new ListItem();
                        objItem.Value = "omae" + Path.DirectorySeparatorChar + strFileName;
                        objItem.Name  = LanguageManager.Instance.GetString("Menu_Main_Omae") + ": " + strFileName;
                        lstFiles.Add(objItem);
                    }
                }
            }
            catch
            {
            }

            cboXSLT.ValueMember   = "Value";
            cboXSLT.DisplayMember = "Name";
            cboXSLT.DataSource    = lstFiles;

            cboXSLT.SelectedValue = _strSelectedSheet;
            // If the desired sheet was not found, fall back to the Shadowrun 4 sheet.
            if (cboXSLT.Text == "")
            {
                cboXSLT.SelectedValue = "Shadowrun 4";
            }
            GenerateOutput();
            _blnLoading = false;
        }
示例#27
0
        private void cmdDelete_Click(object sender, EventArgs e)
        {
            if (lstKits.Text == string.Empty)
            {
                return;
            }

            if (MessageBox.Show(LanguageManager.Instance.GetString("Message_DeletePACKSKit").Replace("{0}", lstKits.Text), LanguageManager.Instance.GetString("MessageTitle_Delete"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
            {
                return;
            }

            // Delete the selectec custom PACKS Kit.
            // Find a custom PACKS Kit with the name. This is done without the XmlManager since we need to check each file individually.
            XmlDocument objXmlDocument = new XmlDocument();
            string      strCustomPath  = Path.Combine(GlobalOptions.ApplicationPath(), "data");

            foreach (string strFile in Directory.GetFiles(strCustomPath, "custom*_packs.xml"))
            {
                objXmlDocument.Load(strFile);
                XmlNodeList objXmlPACKSList = objXmlDocument.SelectNodes("/chummer/packs/pack[name = \"" + lstKits.SelectedValue + "\" and category = \"Custom\"]");
                if (objXmlPACKSList.Count > 0)
                {
                    // Read in the entire file.
                    XmlDocument objXmlCurrentDocument = new XmlDocument();
                    objXmlCurrentDocument.Load(strFile);

                    FileStream    objStream = new FileStream(strFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                    XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.Unicode);
                    objWriter.Formatting  = Formatting.Indented;
                    objWriter.Indentation = 1;
                    objWriter.IndentChar  = '\t';
                    objWriter.WriteStartDocument();

                    // <chummer>
                    objWriter.WriteStartElement("chummer");
                    // <packs>
                    objWriter.WriteStartElement("packs");

                    // If this is not a new file, write out the current contents.
                    XmlNodeList objXmlNodeList = objXmlCurrentDocument.SelectNodes("/chummer/packs/*");
                    foreach (XmlNode objXmlNode in objXmlNodeList)
                    {
                        if (objXmlNode["name"].InnerText != lstKits.SelectedValue.ToString())
                        {
                            // <pack>
                            objWriter.WriteStartElement("pack");
                            objXmlNode.WriteContentTo(objWriter);
                            // </pack>
                            objWriter.WriteEndElement();
                        }
                    }

                    // </packs>
                    objWriter.WriteEndElement();
                    // </chummer>
                    objWriter.WriteEndElement();

                    objWriter.WriteEndDocument();
                    objWriter.Close();
                    objStream.Close();
                }
            }

            // Reload the PACKS files since they have changed.
            _objXmlDocument = XmlManager.Instance.Load("packs.xml");
            cboCategory_SelectedIndexChanged(sender, e);
        }
示例#28
0
        private void mnuNewCritter_Click(object sender, EventArgs e)
        {
            Character objCharacter = new Character();

            if (Directory.GetFiles(Path.Combine(GlobalOptions.ApplicationPath(), "settings"), "*.xml").Count() > 1)
            {
                frmSelectSetting frmPickSetting = new frmSelectSetting();
                frmPickSetting.ShowDialog(this);

                if (frmPickSetting.DialogResult == DialogResult.Cancel)
                {
                    return;
                }

                objCharacter.SettingsFile = frmPickSetting.SettingsFile;
            }
            else
            {
                string strSettingsFile = Directory.GetFiles(Path.Combine(GlobalOptions.ApplicationPath(), "settings"), "*.xml")[0];
                strSettingsFile           = strSettingsFile.Replace(Path.Combine(GlobalOptions.ApplicationPath(), "settings"), string.Empty);
                strSettingsFile           = strSettingsFile.Replace(Path.DirectorySeparatorChar, ' ').Trim();
                objCharacter.SettingsFile = strSettingsFile;
            }

            // Override the defaults for the setting.
            objCharacter.IgnoreRules = true;
            objCharacter.IsCritter   = true;
            objCharacter.BuildMethod = CharacterBuildMethod.BP;
            objCharacter.BuildPoints = 0;

            // Make sure that Running Wild is one of the allowed source books since most of the Critter Powers come from this book.
            bool blnRunningWild = false;

            blnRunningWild = (objCharacter.Options.Books.Contains("RW"));

            if (!blnRunningWild)
            {
                MessageBox.Show(LanguageManager.Instance.GetString("Message_Main_RunningWild"), LanguageManager.Instance.GetString("MessageTitle_Main_RunningWild"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // Show the Metatype selection window.
            frmMetatype frmSelectMetatype = new frmMetatype(objCharacter);

            frmSelectMetatype.XmlFile = "critters.xml";
            frmSelectMetatype.ShowDialog();

            if (frmSelectMetatype.DialogResult == DialogResult.Cancel)
            {
                return;
            }

            // Add the Unarmed Attack Weapon to the character.
            try
            {
                XmlDocument objXmlDocument = XmlManager.Instance.Load("weapons.xml");
                XmlNode     objXmlWeapon   = objXmlDocument.SelectSingleNode("/chummer/weapons/weapon[id = \"" + Constants.UnarmedAttack + "\"]");
                TreeNode    objDummy       = new TreeNode();
                Weapon      objWeapon      = new Weapon(objCharacter);
                objWeapon.Create(objXmlWeapon, objCharacter, objDummy, null, null, null);
                objCharacter.Weapons.Add(objWeapon);
            }
            catch
            {
            }

            frmCreate frmNewCharacter = new frmCreate(objCharacter);

            frmNewCharacter.MdiParent   = this;
            frmNewCharacter.WindowState = FormWindowState.Maximized;
            frmNewCharacter.Show();

            objCharacter.CharacterNameChanged += objCharacter_CharacterNameChanged;
        }