Load() public method

public Load ( Stream inStream ) : void
inStream Stream
return void
Exemplo n.º 1
0
        public XmlWriter()
        {
            string filename = AppDomain.CurrentDomain.BaseDirectory.ToString() + @"/Table1.xml";

            XmlDocument xmlDoc = new XmlDocument();

            try
            {
                xmlDoc.Load(filename);
            }
            catch (System.IO.FileNotFoundException ex)
            {
                Console.WriteLine(ex);
                XmlTextWriter xmlWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
                xmlWriter.Formatting = Formatting.Indented;
                xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
                xmlWriter.WriteStartElement("Table");
                xmlWriter.WriteStartElement("Players");
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("Dealer");
                xmlWriter.WriteStartElement("DealerCards");
                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndElement();
                xmlWriter.Close();
                xmlDoc.Load(filename);
            }
        }
 public static XmlDocument LoadXML(string URL, string xmlFileName)
 {
     XmlDocument xml = new XmlDocument();
     string dire = Directory.GetCurrentDirectory();
     string xmlFile = dire + "\\XML\\" + xmlFileName;
     if (File.Exists(xmlFile))
     {
         FileStream stream = new FileStream(xmlFile, FileMode.Open);
         xml.Load(stream);
         stream.Close();
     }
     else
     {
         try
         {
             xml.Load(URL);
         }
         catch (System.Exception)
         {
             Console.WriteLine("Date Feed Not Found.");
             xml = null;
             return xml;
         }
         Console.WriteLine("Date Feed Updated.");
         FileStream stream = new FileStream(xmlFile, FileMode.Create);
         xml.Save(stream);
         stream.Close();
     }
     return xml;
 }
Exemplo n.º 3
0
        public static string getCompList(bool test)
        {
            string sources="";
            try
            {
                XmlDocument doc = new XmlDocument();

                if (test)
                {
                    doc.Load(AppEnvironment.strListFileTest);
                }
                else
                {
                    doc.Load(AppEnvironment.strListFile);
                }

                sources = doc.DocumentElement["others"].ChildNodes[1].InnerText;
            }
            catch ( System.IO.IOException e )
            {
                //saveConfigXML();
                sources = AppEnvironment.strDefaultPath;
                Console.Out.WriteLine ( "Error: " + e.Message );
            }

            return sources;
        }
Exemplo n.º 4
0
 public void writeOptions()
 {
     Directory.CreateDirectory(OPTIONS_PATH);
     XmlDocument xmlDoc = new XmlDocument();
     try
     {
         xmlDoc.Load(OPTIONS_FILE);
     }
     catch (System.IO.FileNotFoundException)
     {
         //if file is not found, create a new xml file
         XmlTextWriter xmlWriter = new XmlTextWriter(OPTIONS_FILE, System.Text.Encoding.UTF8);
         xmlWriter.Formatting = Formatting.Indented;
         xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
         xmlWriter.WriteStartElement("root");
         //If WriteProcessingInstruction is used as above,
         //Do not use WriteEndElement() here
         //xmlWriter.WriteEndElement();
         //it will cause the <Root> to be &ltRoot />
         xmlWriter.Close();
         xmlDoc.Load(OPTIONS_FILE);
     }
     XmlNode root = xmlDoc.DocumentElement;
     root.AppendChild(asXML(root));
     xmlDoc.Save(OPTIONS_FILE);
 }
Exemplo n.º 5
0
        static void Main()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("../../../catalogue.xml");
            XmlNode catalogue = doc.DocumentElement;

            foreach (XmlNode album in catalogue.SelectNodes("album"))
            {
                int albumPrice = int.Parse(album["price"].InnerText);

                if (albumPrice > 20)
                {
                    catalogue.RemoveChild(album);
                }
            }

            doc.Save("../../../catalogueReduced.xml");
            doc.Load("../../../catalogueReduced.xml");
            XmlNode updated = doc.DocumentElement;

            foreach (XmlNode album in updated.ChildNodes)
            {
                Console.WriteLine("album: {0} price: {1} ", album["name"].InnerText, album["price"].InnerText);
            }
        }
        public void RecordAgent()
        {
            #region CLIENT RECORD

            if (!File.Exists(Generate.xmlPath))
                return;

            XmlDocument xmld = new XmlDocument();
            try { xmld.Load(Generate.xmlPath); }
            catch { Thread.Sleep(50); xmld.Load(Generate.xmlPath); }
            foreach (XmlElement xmle in xmld.GetElementsByTagName("clients"))
            {
                Coming c = new Coming();
                c.id = xmle["id"].InnerText;
                c.lep = xmle["lep"].InnerText;
                c.macAddress = xmle["macAddress"].InnerText;
                c.licence = xmle["licence"].InnerText;
                c.Session = Convert.ToInt32(xmle["Session"].InnerText);
                c.port = Convert.ToInt32(xmle["port"].InnerText);
                c.Address = xmle["Address"].InnerText;
                c.cep = new IPEndPoint(IPAddress.Parse(c.Address), c.port);

                Agent.clients.Add(c.id, c);
            }
            try { xmld.Save(Generate.xmlPath); }
            catch { Thread.Sleep(50); xmld.Save(Generate.xmlPath); }

            Generate.isFirst = false;
            ("SERVER WORKING FIRST TIME & TRANSFERRED XML DATA TO Agent.clients").p2pDEBUG();
            #endregion
        }
Exemplo n.º 7
0
        public Battle(SPRWorld sprWorld, int botHalfWidth, World world, int currentLevel)
        {
            this.sprWorld = sprWorld;
            this.botHalfWidth = botHalfWidth;
            this.world = world;

            xmlDoc = new XmlDocument();

            if (nextAllies == "")
            {
                xmlDoc.Load("Games/SuperPowerRobots/Storage/Allies.xml");
            }
            else
            {
                xmlDoc.LoadXml(nextAllies);
            }

            //xmlDoc.

            XmlNodeList nodes = xmlDoc.GetElementsByTagName("Bot");

            Vector2[] edges = { new Vector2(-botHalfWidth, -botHalfWidth) * Settings.MetersPerPixel, new Vector2(botHalfWidth, -botHalfWidth) * Settings.MetersPerPixel, new Vector2(botHalfWidth, botHalfWidth) * Settings.MetersPerPixel, new Vector2(-botHalfWidth, botHalfWidth) * Settings.MetersPerPixel };

            CreateBots(nodes, edges);

            xmlDoc.Load("Games/SuperPowerRobots/Storage/Battles.xml");

            nodes = xmlDoc.GetElementsByTagName("Level");

            nodes = nodes[currentLevel].ChildNodes;

            CreateBots(nodes, edges);
        }
Exemplo n.º 8
0
        // Accumulation format is now called Victory.
        private static void Upgrades0210()
        {
            var xml = new XmlDocument();
            if (Config.Settings.SeparateEventFiles)
            {
                var targetPath = Path.Combine(Program.BasePath, "Tournaments");
                if (!Directory.Exists(targetPath)) Directory.CreateDirectory(targetPath);
                var files = new List<string>(Directory.GetFiles(targetPath, "*.tournament.dat",
                    SearchOption.TopDirectoryOnly));
                files.AddRange(Directory.GetFiles(targetPath, "*.league.dat",
                    SearchOption.TopDirectoryOnly));
                foreach (string filename in files)
                {
                    xml.Load(filename);
                    var oldNodes = xml.SelectNodes("//Events/Tournaments/Tournament/Format[. = 'Accumulation']");
                    if (oldNodes != null)
                        foreach (XmlNode oldNode in oldNodes)
                            oldNode.InnerText = "Victory";
                    oldNodes = xml.SelectNodes("//Events/Leagues/League/Format[. = 'Accumulation']");
                    if (oldNodes != null)
                        foreach (XmlNode oldNode in oldNodes)
                            oldNode.InnerText = "Victory";

                    var writer = new XmlTextWriter(new FileStream(filename, FileMode.Create), null)
                        {
                            Formatting = Formatting.Indented,
                            Indentation = 1,
                            IndentChar = '\t'
                        };

                    xml.WriteTo(writer);
                    writer.Flush();
                    writer.Close();
                }
            }
            else if (File.Exists(Path.Combine(Program.BasePath, "Events.dat")))
            {
                xml.Load(Path.Combine(Program.BasePath, "Events.dat"));
                var oldNodes = xml.SelectNodes("//Events/Tournaments/Tournament/Format[. = 'Accumulation']");
                if (oldNodes != null)
                    foreach (XmlNode oldNode in oldNodes)
                        oldNode.InnerText = "Victory";
                oldNodes = xml.SelectNodes("//Events/Leagues/League/Format[. = 'Accumulation']");
                if (oldNodes != null)
                    foreach (XmlNode oldNode in oldNodes)
                        oldNode.InnerText = "Victory";

                var writer = new XmlTextWriter(new FileStream(Path.Combine(Program.BasePath,
                                                                           "Events.dat"), FileMode.Create), null)
                {
                    Formatting = Formatting.Indented,
                    Indentation = 1,
                    IndentChar = '\t'
                };

                xml.WriteTo(writer);
                writer.Flush();
                writer.Close();
            }
        }
Exemplo n.º 9
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="optionsRoot">The options root object</param>
		/// <param name="context">The file name for XML Document</param>
		void IVisitorWithContext.Visit(UIOptionRootType optionsRoot, object context)
		{
			XmlDocument xmlDoc = new XmlDocument();
			Stream stream = context as Stream;
			if (stream == null)
			{
				xmlDoc.Load((string) context);
			}
			else
			{
				xmlDoc.Load(stream);
			}

			XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
			nsmgr.AddNamespace("ws", "http://schemas.workshare.com/Workshare.OptionMap.xsd");

			string xpath = "ws:OptionMap/ws:Category";
			XmlNodeList categories = xmlDoc.SelectNodes(xpath, nsmgr);

			foreach (XmlNode node in categories)
			{
				UIOptionCategoryType category = new UIOptionCategoryType();
				optionsRoot.Categories.Add(category);
				category.Accept(this, node);
			}
		}
Exemplo n.º 10
0
        private static XmlDocument GetXmlDocument(string path)
        {
            using (Stream s = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                byte[] buffer = new byte[2];
                s.Read(buffer, 0, 2);
                s.Position = 0;
                XmlDocument document = new XmlDocument();
                XmlReaderSettings xrSettings = new XmlReaderSettings();
                xrSettings.DtdProcessing = DtdProcessing.Ignore;
                // if first two bytes are "MZ" then we're looking at an .exe or a .dll not a .manifest
                if ((buffer[0] == 0x4D) && (buffer[1] == 0x5A))
                {
                    Stream m = EmbeddedManifestReader.Read(path);
                    if (m == null)
                        throw new BadImageFormatException(null, path);

                    using (XmlReader xr = XmlReader.Create(m, xrSettings))
                    {
                        document.Load(xr);
                    }
                }
                else
                {
                    using (XmlReader xr = XmlReader.Create(s, xrSettings))
                    {
                        document.Load(xr);
                    }
                }

                return document;
            }
        }
Exemplo n.º 11
0
        private void _openBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                if (_urlBtn.IsChecked==true)
                {
                    doc.Load(_inputTbx.Text);
                }
                if (_streamBtn.IsChecked==true)
                {
                    FileStream stream = new FileStream(_inputTbx.Text, FileMode.Open);
                    doc.Load(stream);
                    stream.Close();
                }
                if (_stringBtn.IsChecked == true)
                {
                    doc.LoadXml(_inputTbx.Text);
                }

                MessageBox.Show(doc.DocumentElement.Name);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemplo n.º 12
0
 void GetInfo()
 {
     // создаем xml-документ
     XmlDocument xmlDocument = new XmlDocument ();
     // делаем запрос на получение имени пользователя
     WebRequest webRequest = WebRequest.Create ("https://api.vk.com/method/users.get.xml?&access_token=" + token);
     WebResponse webResponse = webRequest.GetResponse ();
     Stream stream = webResponse.GetResponseStream ();
     xmlDocument.Load (stream);
     string name =  xmlDocument.SelectSingleNode ("response/user/first_name").InnerText;
     // делаем запрос на проверку,
     webRequest = WebRequest.Create ("https://api.vk.com/method/groups.isMember.xml?group_id=20629724&access_token=" + token);
     webResponse = webRequest.GetResponse ();
     stream = webResponse.GetResponseStream ();
     xmlDocument.Load (stream);
     bool habrvk = (xmlDocument.SelectSingleNode ("response").InnerText =="1");
     // выводим диалоговое окно
     var builder = new AlertDialog.Builder (this);
     // пользователь состоит в группе "хабрахабр"?
     if (!habrvk) {
         builder.SetMessage ("Привет, "+name+"!\r\n\r\nТы не состоишь в группе habrahabr.Не хочешь вступить?");
         builder.SetPositiveButton ("Да", (o, e) => {
             // уточнив, что пользователь желает вступить, отправим запрос
             webRequest = WebRequest.Create ("https://api.vk.com/method/groups.join.xml?group_id=20629724&access_token=" + token);
              webResponse = webRequest.GetResponse ();
         });
         builder.SetNegativeButton ("Нет", (o, e) => {
         });
     } else {
         builder.SetMessage ("Привет, "+name+"!\r\n\r\nОтлично! Ты состоишь в группе habrahabr.");
         builder.SetPositiveButton ("Ок", (o, e) => {
         });
     }
     builder.Create().Show();
 }
Exemplo n.º 13
0
        /// <summary>
        /// 加载权限数据
        /// </summary>
        private void Load()
        {
            //内网IP
            LoadInnerIPList();
            string fileName = PermissionFilePath;
            fileName = ConfigurationManager.AppSettings[FilePathAppSettings] ?? fileName;
            //框架权限IP
            var doc = new XmlDocument();
            if (File.Exists(fileName))
            {
                doc.Load(fileName);
            }
            else
            {
                using (Stream stream = typeof(PermissionController).Assembly.GetManifestResourceStream(SourceAuthorityFile))
                {
                    XmlTextReader reader = new XmlTextReader(stream);
                    doc.Load(reader);
                }
            }

            IpViewList = LoadPermissionIPs(xPathView, doc);
            IpChangeList = LoadPermissionIPs(xPathChange, doc);
            LoadConfigIPList(ConfigurationManager.AppSettings[ModifyConfigIPList]);
            

        }
Exemplo n.º 14
0
		public static int sMain (string [] args)
		{
			if (args.Length < 1) {
				Console.WriteLine ("Usage: monodoc2wiki monodoc_xmlfile");
				return 1;
			}

			XmlDocument doc = new XmlDocument ();
#if VALIDATION
			XmlTextReader xr = new XmlTextReader (args [0]);
			RelaxngPattern rp = RncParser.ParseRnc (new StreamReader ("CLILibraryTypes.rnc"));
Console.Error.WriteLine ("**** READY ****");
rp.Compile ();
Console.Error.WriteLine ("**** DONE ****");
			RelaxngValidatingReader rvr = new RelaxngValidatingReader (xr, rp);
			doc.Load (rvr);
			rvr.Close ();
#else
			doc.Load (args [0]);
#endif
			Monodoc2Wiki instance = new Monodoc2Wiki ();
			string ret = instance.ProcessNode (doc.DocumentElement);

			Console.WriteLine (ret);

			return 0;
		}
Exemplo n.º 15
0
        public Model Load(string fileName)
        {
            var document = new XmlDocument();

            if (fileName.EndsWith(".tcn"))
            {
                var file = new ZipFile(new FileStream(fileName, FileMode.Open, FileAccess.Read));

                var enumerator = file.GetEnumerator();

                while (enumerator.MoveNext())
                {
                    if (((ZipEntry)enumerator.Current).Name.EndsWith(".xml"))
                    {
                        document.Load(file.GetInputStream((ZipEntry)enumerator.Current));
                        break;
                    }
                }
            }
            else if (fileName.EndsWith(".xml"))
                document.Load(fileName);
            else
                throw new FileLoadException();

            var tcnModel = new TCNFile();
            tcnModel.Parse(document.DocumentElement);

            return tcnModel.Convert();
        }
Exemplo n.º 16
0
        /// <summary>
        /// 加载XML文件
        /// </summary>
        /// <param name="xmlDoc">XML文件</param>
        /// <param name="strXmlPath">XML文件的路径</param>
        /// <param name="strRoot">根节点的值</param>
        public static void LoadXmlFile(XmlDocument xmlDoc, string strXmlPath, string strRoot)
        {
            if (strXmlPath == string.Empty)
            {
                return;
            }
            if (xmlDoc == null)
            {
                return;
            }
            if (System.IO.File.Exists(strXmlPath))
            {
                xmlDoc.Load(strXmlPath);
            }
            else
            {
                XmlNode xmlNode = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
                xmlDoc.AppendChild(xmlNode);

                XmlElement xmlElement = xmlDoc.CreateElement("", "Root", "");
                XmlText xmlText = xmlDoc.CreateTextNode(strRoot);
                xmlElement.AppendChild(xmlText);
                xmlDoc.AppendChild(xmlElement);
                try
                {
                    xmlDoc.Save(strXmlPath);
                    xmlDoc.Load(strXmlPath);
                }
                catch (System.Exception e)
                {
                    return;
                }
            }
        }
Exemplo n.º 17
0
        public Workspace(string workspacepath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(workspacepath); //加载XML文档
            XmlNode Node = xmlDoc.SelectSingleNode("workspace");
            XmlNode IDNode = Node.FirstChild ;
            XmlNode NameNode = Node.LastChild;
            if (IDNode != null)
            {
                ID = IDNode.InnerText;
            }
            if (NameNode != null)
            {
                Name = NameNode.InnerText;
            }

            string namespacepath = workspacepath.Replace("workspace.xml", "namespace.xml");
            xmlDoc.Load(namespacepath);
            Node = xmlDoc.SelectSingleNode("namespace");
            XmlNode PrefixNode = Node.ChildNodes[1];
            XmlNode UriNode = Node.ChildNodes[2];

            if (PrefixNode != null)
            {
                this.Prefix = PrefixNode.InnerText;
                this.URI = UriNode.InnerText;
            }
        }
Exemplo n.º 18
0
        public XmlDocument GetXMLDocument(string path)
        {
            XmlDocument xmlDocument = new XmlDocument();

            try
            {
                if (path.StartsWith("http"))
                {
                    HttpWebRequest request = new HTTPConnector().BuildWebRequest(path, "text/xml");
                    using (WebResponse response = request.GetResponse())
                    {
                        Stream xmlStream = response.GetResponseStream();
                        xmlDocument.Load(xmlStream);
                        xmlStream.Close();
                        response.Close();
                    }
                }
                else
                {
                    xmlDocument.Load(path);
                }
            }
            catch (Exception exception)
            {
                ErrorService.Log("XMLConnector", "GetXMLDocument", path, exception);
            }

            return xmlDocument;
        }
Exemplo n.º 19
0
        public void LoadExternalAppsFromXML()
        {
            #if !PORTABLE
            var oldPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), GeneralAppInfo.ProductName, SettingsFileInfo.ExtAppsFilesName);
            #endif
            var newPath = Path.Combine(SettingsFileInfo.SettingsPath, SettingsFileInfo.ExtAppsFilesName);
            var xDom = new XmlDocument();
            if (File.Exists(newPath))
            {
                Logger.Instance.Info($"Loading External Apps from: {newPath}");
                xDom.Load(newPath);
            }
            #if !PORTABLE
            else if (File.Exists(oldPath))
            {
                Logger.Instance.Info($"Loading External Apps from: {oldPath}");
                xDom.Load(oldPath);

            }
            #endif
            else
            {
                Logger.Instance.Warn("Loading External Apps failed: Could not FIND file!");
                return;
            }

            if (xDom.DocumentElement == null)
            {
                Logger.Instance.Warn("Loading External Apps failed: Could not LOAD file!");
                return;
            }

            foreach (XmlElement xEl in xDom.DocumentElement.ChildNodes)
            {
                var extA = new ExternalTool
                {
                    DisplayName = xEl.Attributes["DisplayName"].Value,
                    FileName = xEl.Attributes["FileName"].Value,
                    Arguments = xEl.Attributes["Arguments"].Value
                };

                if (xEl.HasAttribute("WaitForExit"))
                {
                    extA.WaitForExit = bool.Parse(xEl.Attributes["WaitForExit"].Value);
                }

                if (xEl.HasAttribute("TryToIntegrate"))
                {
                    extA.TryIntegrate = bool.Parse(xEl.Attributes["TryToIntegrate"].Value);
                }

                Logger.Instance.Info($"Adding External App: {extA.DisplayName} {extA.FileName} {extA.Arguments}");
                Runtime.ExternalTools.Add(extA);
            }

            _MainForm.SwitchToolBarText(Convert.ToBoolean(mRemoteNG.Settings.Default.ExtAppsTBShowText));

            frmMain.Default.AddExternalToolsToToolBar();
        }
Exemplo n.º 20
0
 public static void SetRZMStr(string rzmStr)
 {
     XmlDocument document = new XmlDocument();
     document.Load(HttpContext.Current.Server.MapPath(@"~/kycon.config"));
     XmlNode node = document.ChildNodes[1];
     node.ChildNodes[0].ChildNodes[1].Attributes["value"].Value = rzmStr;
     document.Load(HttpContext.Current.Server.MapPath(@"~/kycon.config"));
 }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            string token = "your-voice-token-goes-here";
            string conferenceID = "my-test-conference";

            // An array of numbers to call and join to the conference.
            string[] numbersToCall = new string[] { "13034567890", "13034567891" };

            // SIP endpoint for a simple Tropo JavaScript app to play a message to the conference. See README file
            string conferenceTimer = "sip:[email protected]";

            // the length of time to wait before playing the conference message.
            int timer = 60000;
            
            // A collection to hold the parameters we want to send to the Tropo Session API.
            IDictionary<string, string> parameters = new Dictionary<String, String>();

            // Instantiate a new instance of the Tropo object.
            Tropo tropo = new Tropo();

            // Create an XML doc to hold the response from the Tropo Session API.
            XmlDocument doc = new XmlDocument();

            // Add the conferencce ID to the paramters collection.
            parameters.Add("conferenceID", conferenceID);

            foreach (string number in numbersToCall)
            {
                // Add the number to call to the parameters collection.
                parameters.Add("callToNumber", number);

                // Make API call.
                Console.WriteLine("Sending API request for: " + number);
                doc.Load(tropo.CreateSession(token, parameters));
                Console.WriteLine("Result: " + doc.SelectSingleNode("session/success").InnerText.ToUpper());
                Console.WriteLine("Token: " + doc.SelectSingleNode("session/token").InnerText);
                Console.WriteLine("=============================");

                // Remove the callToNumber key so we can reset in next loop.
                parameters.Remove("callToNumber");                
            }

            // Sleep for x seconds.
            Thread.Sleep(timer);

            // Send reminder message to the conference.
            Console.WriteLine("Sending conference time reminder.");
            parameters.Add("callToNumber", conferenceTimer);
            doc.Load(tropo.CreateSession(token, parameters));
            Console.WriteLine("Result: " + doc.SelectSingleNode("session/success").InnerText.ToUpper());
            Console.WriteLine("Token: " + doc.SelectSingleNode("session/token").InnerText);
            Console.WriteLine("=============================");

            Console.Read();
        }
Exemplo n.º 22
0
        public void LogIt(DateTime exceptionDate, string exceptionSource, string exceptionMessage)
        {
            Console.WriteLine(" XML Logger ");

            try
            {
                const string fileName = "appLog.xml";
                var xmlDocument = new XmlDocument();

                try
                {
                    xmlDocument.Load(fileName);
                }
                catch (FileNotFoundException)
                {
                    var xmlWriter = new XmlTextWriter(fileName, System.Text.Encoding.UTF8) { Formatting = Formatting.Indented };
                    xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
                    xmlWriter.WriteStartElement("Logs");
                    xmlWriter.Close();
                    xmlDocument.Load(fileName);
                }

                XmlNode logRoot = xmlDocument.DocumentElement;
                XmlElement logElement = xmlDocument.CreateElement("log");
                XmlElement dateElement = xmlDocument.CreateElement("exceptionDate");
                XmlElement sourceElement = xmlDocument.CreateElement("exceptionSource");
                XmlElement messageElement = xmlDocument.CreateElement("exceptionMessage");

                XmlText dateText = xmlDocument.CreateTextNode("date");
                dateText.Value = exceptionDate.ToString();
                XmlText sourceText = xmlDocument.CreateTextNode("source");
                sourceText.Value = exceptionSource;
                XmlText messageText = xmlDocument.CreateTextNode("message");
                messageText.Value = exceptionMessage;

                logRoot.AppendChild(logElement);

                dateElement.AppendChild(dateText);
                sourceElement.AppendChild(sourceText);
                messageElement.AppendChild(messageText);

                logElement.AppendChild(dateElement);
                logElement.AppendChild(sourceElement);
                logElement.AppendChild(messageElement);

                xmlDocument.Save(fileName);
            }
            catch (Exception)
            {
                Console.WriteLine(" Ya mejor lo escribo en pantalla ");
            }
        }
Exemplo n.º 23
0
		//•	page-start-number: Page start number (default: 1)
		//•	page-setup-paper-width: Paper width in TWIPS (default: 11907 TWIPS = 21 cm, i.e. A4 format)
		//•	page-setup-paper-height: Paper height in TWIPS (default: 16840 TWIPS = 29.7 cm, i.e. A4 format)
		//•	page-setup-margin-top: Top margin in TWIPS (default: 1440 TWIPS = 1 inch = 2.54 cm)
		//•	page-setup-margin-bottom: Bottom margin in TWIPS (default: 1440 TWIPS = 1 inch = 2.54 cm)
		//•	page-setup-margin-left: Left margin in TWIPS (default: 1134 TWIPS = 2 cm)
		//•	page-setup-margin-right: Right margin in TWIPS (default: 1134 TWIPS = 2 cm)
		//•	font-size-default: Default font size in TWIPS (default: 20 TWIPS = 10 pt.)
		//•	font-name-default: Default font name (default: 'Times New Roman')
		//•	font-name-fixed: Default font name for fixed-width text, like PRE or CODE (default: 'Courier New')
		//•	font-name-barcode: Barcode font name (default: '3 of 9 Barcode')
		//•	header-font-size-default: Header default font size in TWIPS (default: 14 TWIPS = 7 pt.)
		//•	header-distance-from-edge: Default distance between top of page and top of header, in TWIPS (default: 720 TWIPS = 1.27 cm)
		//•	header-indentation-left: Header left indentation in TWIPS (default: 0)
		//•	footer-font-size-default: Footer default font size in TWIPS (default: 14 TWIPS = 7 pt.)
		//•	footer-distance-from-edge: Default distance between bottom of page and bottom of footer, in TWIPS (default: 720 TWIPS = 1.27 cm)
		//•	use-default-footer: Boolean flag: 1 to use default footer (page number and date) or 0 no footer (default: 1)
		//•	document-protected: Boolean flag: 1 protected (cannot be modified) or 0 unprotected (default: 1)
		//•	normalize-space: Boolean flag: 1 spaces are normalized and trimmed, or 0 no normalization no trim (default: 0)
		//•	my-normalize-space: Boolean flag: 1 spaces are normalized (NOT TRIMMED), or 0 no normalization (default: 1)


		public static string Html2Rtf(string html, NameValueCollection parameters)
		{
			// Load data.
			var xml = new System.Xml.XmlDocument();
			xml.Load(Helper.GetResource("Help.htm"));
			xml.DocumentElement.SetAttribute("xmlns", "http://www.w3.org/1999/xhtml");
			xml.DocumentElement.SetAttribute("xmlns:xhtml2rtf", "http://www.lutecia.info/download/xmlns/xhtml2rtf");
			//xml.DocumentElement.SetAttribute("SelectionLanguage", "XPath");
			//xml.DocumentElement.SetAttribute("SelectionNamespaces", "xmlns='http://www.w3.org/1999/xhtml' xmlns:xhtml='http://www.w3.org/1999/xhtml'");
			xml.Load(new StringReader(xml.OuterXml));
			// Load style sheet.
			var xslDoc = new System.Xml.XmlDocument();
			xslDoc.Load(Helper.GetResource("xhtml2rtf.xsl"));
			//xslDoc.DocumentElement.SetAttribute("SelectionLanguage", "XPath");
			//xslDoc.DocumentElement.SetAttribute("SelectionNamespaces", "xmlns:xhtml='http://www.w3.org/1999/xhtml' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'");
			//xslDoc.Load(new StringReader(xslDoc.OuterXml));
			// Create namespace manager.
			XmlNamespaceManager man = new XmlNamespaceManager(xslDoc.NameTable);
			man.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
			
			// Set parameters in stylesheet
			if (parameters != null)
			{
				foreach (var name in parameters.AllKeys)
				{
					var value = parameters[name];
					var xmlParam = xslDoc.DocumentElement.SelectSingleNode("//xsl:param[@name='" + name + "']", man);
					if (xmlParam != null)
					{
						var xmlParamValue = xmlParam.SelectSingleNode("@select", man);
						if (xmlParamValue != null)
						{
							xmlParamValue.InnerText = value;
						}
					}
				}
			}
			// Load the String into a TextReader
			System.IO.StringReader tr = new System.IO.StringReader(xslDoc.OuterXml);
			// Use that TextReader as the Source for the XmlTextReader
			System.Xml.XmlReader xr = new System.Xml.XmlTextReader(tr);
			// Create a new XslTransform class
			var xsl = new System.Xml.Xsl.XslCompiledTransform(true);
			// Load the XmlReader StyleSheet into the XslTransform class
			xsl.Load(xr, new XsltSettings(false, true), (XmlResolver)null);
			// Create output
			var sb = new System.Text.StringBuilder();
			var tw = new System.IO.StringWriter(sb);
			xsl.Transform(xml, (XsltArgumentList)null, tw);
			// Return RTF document.
			return sb.ToString();
		}
Exemplo n.º 24
0
        private void GetNews(string blobXmlFilePath = "")
        {
            try
            {
                XmlDocument xdoc = new XmlDocument();
                string newsXml = string.Empty;

                if (blobXmlFilePath == "")
                {
                    string basePath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["MovieList"]);
                    string filePath = Path.Combine(basePath, "News.xml");
                    xdoc.Load(filePath);
                }
                else
                {
                    xdoc.Load(blobXmlFilePath);
                }

                var items = xdoc.SelectNodes("News/Link");
                if (items != null)
                {
                    foreach (XmlNode item in items)
                    {
                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(item.InnerText);
                        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            #region Get News Content
                            Stream receiveStream = response.GetResponseStream();
                            StreamReader readStream = null;
                            if (response.CharacterSet == null)
                                readStream = new StreamReader(receiveStream);
                            else
                                readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));

                            newsXml = readStream.ReadToEnd();
                            List<NewsEntity> news = ParseNewsItems(newsXml, item.Attributes["type"].Value);
                            TableManager tblMgr = new TableManager();
                            tblMgr.UpdateNewsById(news);
                            response.Close();
                            readStream.Close();
                            #endregion
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }
        internal static void Main()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("../../../correctXML.xml");
            doc.Schemas.Add("urn:catalogueSchema", "../../../catalogueSchema.xsd");

            ValidationEventHandler eventhandler = new ValidationEventHandler(ValidateEventHandler);
            doc.Validate(eventhandler);

            // I Just delete albums element.
            doc.Load("../../../invalidXML.xml");
            doc.Validate(eventhandler);
        }
Exemplo n.º 26
0
 public static XmlDocument LoadXml(string path)
 {
     XmlDocument doc = new XmlDocument();
     for (int i = 0; i < Directories.Length; i++)
     {
         if (File.Exists(Directories[i] + path))
         {
             doc.Load(Directories[i] + path);
             return doc;
         }
     }
     doc.Load(path);
     return doc;
 }
Exemplo n.º 27
0
        private void Form2_Load(object sender, EventArgs e)
        {
            if (checkMonth(AMCDir) == false)
            {
                MessageBox.Show("光碟月份有誤");
                this.Close();
                return;
            }

            XmlDocument xd = new XmlDocument();
            xd.Load(AMCDir + "data\\lessons.xml");
            foreach (XmlNode day in xd.SelectSingleNode("Lesson").ChildNodes)
            {
                if (day.SelectSingleNode("Date").InnerText == date.ToString("dd"))
                {
                    lessonName = day.SelectSingleNode("Lesn").InnerText;
                    label_lessonName.Text = lessonName + "  " + day.SelectSingleNode("Chn").InnerText;
                    break;
                }
            }

            xd.Load(AMCDir + "data\\" + lessonName + ".xml");
            if (xd.SelectSingleNode("data").SelectNodes("i_Lesn").Count == 0)
            {
                Label txt = new Label();
                txt.Text = "本日無課文內容";
                txt.Parent = flowLayoutPanel1;
            }
            else
            {
                XmlNodeList article = xd.SelectSingleNode("data").SelectSingleNode("i_Lesn").SelectNodes("i_Prt");
                foreach (XmlNode paragraph in article)
                {
                    Label line = new Label();
                    line.AutoSize = false;
                    line.Width = 2000;
                    line.Height = 14;
                    line.Parent = flowLayoutPanel1;
                    foreach (XmlNode sentence in paragraph.SelectSingleNode("i_Stncs").SelectNodes("i_Stnc"))
                    {
                        Label txt = new Label();
                        txt.Text = sentence.SelectSingleNode("i_Eng").InnerText;
                        txt.AutoSize = true;
                        txt.Font = new System.Drawing.Font("Calibri", 14);
                        txt.Parent = flowLayoutPanel1;
                    }
                }
            }
        }
Exemplo n.º 28
0
 public static ColumnInfo[] ReadColumnInfos(string name, Type xmlType)
 {
     string basePath = System.Web.HttpContext.Current.Request.MapPath("") + "\\";
     XmlDocument doc = new XmlDocument();
     XmlNode node;
     if (System.IO.File.Exists(basePath + name + ".model"))
     {
         doc.Load(basePath + name + ".model");
         node = doc.SelectSingleNode("Model");
     }
     else if (System.IO.File.Exists(basePath + "domain.model"))
     {
         doc.Load(basePath + "domain.model");
         node = doc.SelectSingleNode("//Model[@name,'" + name + "']");
     }
     else
         return null;
     List<ColumnInfo> columns = new List<ColumnInfo>();
     XmlNodeList fields = node.SelectNodes("Column");
     foreach (XmlNode fieldNode in fields)
     {
         string columnName = fieldNode.Attributes["Name"].Value;
         string typeName = fieldNode.Attributes["Type"].Value;
         Type columnType = TypeLoader.GetType(typeName);
         DataType dataType = DataType.None;
         if (columnType != null)
         {
             if (columnType.IsEnum)
             {
                 dataType = DataType.None;
             }
             else if (fieldNode.Attributes["Relationship"] == null ||
                 fieldNode.Attributes["Relationship"].Value == "One")
                 dataType = DataType.RecordSelect;
             else
             {
                 dataType = DataType.RecordList;
                 columnType = iRecordListType.MakeGenericType(columnType);
             }
         }
         else
         {
             dataType = (DataType)Enum.Parse(typeof(DataType), typeName);
             columnType = DataTypeHelper.SystemForDataType(dataType);
         }
         columns.Add(new ColumnInfo(columnName, columnType, dataType, xmlType, false));
     }
     return columns.ToArray();
 }
Exemplo n.º 29
0
        private void AccountChart_Load(object sender, EventArgs e)
        {
            ChartPanel.Invalidate();
            #region Theme
            XmlDocument xmlDocTheme = new XmlDocument();
            if (frmMain.strTheme == "Blue")
            {
                xmlDocTheme.Load(Application.StartupPath + "/Theme/Theme-Blue.xml");
            }
            else if (frmMain.strTheme == "White")
            {
                xmlDocTheme.Load(Application.StartupPath + "/Theme/Theme-White.xml");
            }
            else if (frmMain.strTheme == "Simple")
            {
                xmlDocTheme.Load(Application.StartupPath + "/Theme/Theme-Simple.xml");
            }

            foreach (XmlNode node in xmlDocTheme.SelectNodes("Theme/Style"))
            {
                if (frmMain.Decryption(node.SelectSingleNode("Name").InnerText) == frmMain.strTheme)
                {
                    this.BackgroundImage = new Bitmap(myAssembly.GetManifestResourceStream(frmMain.Decryption(node.SelectSingleNode("bg5").InnerText)));
                    break;
                }
            }
            #endregion
            #region Language
            XmlDocument xmlDocLng = new XmlDocument();
            if (frmMain.strLanguage == "English")
            {
                xmlDocLng.Load(Application.StartupPath + "/Language/Language-English.xml");
            }
            else if (frmMain.strLanguage == "Vietnamese")
            {
                xmlDocLng.Load(Application.StartupPath + "/Language/Language-Vietnamese.xml");
            }

            foreach (XmlNode node in xmlDocLng.SelectNodes("Language/Form"))
            {
                if (frmMain.Decryption(node.SelectSingleNode("Name").InnerText) == this.Name)
                {
                    btnSave.Text = frmMain.Decryption(node.SelectSingleNode("btn1").InnerText);
                    btnClose.Text = frmMain.Decryption(node.SelectSingleNode("btn2").InnerText);
                    break;
                }
            }
            #endregion
        }
Exemplo n.º 30
0
		private void Page_Load(object sender, System.EventArgs e)
		{
			// 03/10/2010   Apply full ACL security rules. 
			this.Visible = (Taoqi.Security.AdminUserAccess(m_sMODULE, "import") >= 0);
			if ( !this.Visible )
				return;
			try
			{
				// 10/27/2008   Skip during precompile. 
				if ( !Sql.ToBoolean(Request["PrecompileOnly"]) )
				{
					DataTable dt = Cache.Get("PublicSugarCRMLanguagePacks.xml") as DataTable;
					if ( dt == null )
					{
						XmlDocument xml = new XmlDocument();
						// 12/24/2008   The data needs to be loaded every time. 
						try
						{
#if DEBUG
							xml.Load(Server.MapPath("PublicSugarCRMLanguagePacks.xml"));
#else
							xml.Load("http://demo.Taoqi.com/Administration/Terminology/Import/PublicSugarCRMLanguagePacks.xml");
#endif
						}
						catch
						{
							xml.Load(Server.MapPath("PublicSugarCRMLanguagePacks.xml"));
						}
						dt = XmlUtil.CreateDataTable(xml.DocumentElement, "LanguagePack", new string[] {"Name", "Date", "Description", "URL"});
						Cache.Insert("PublicSugarCRMLanguagePacks.xml", dt, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
					}

					vwMain = new DataView(dt);
					vwMain.RowFilter = "URL > ''";
					vwMain.Sort      = "Name";
					grdMain.DataSource = vwMain ;
					// 12/24/2008   We need to rebind every time.  Pagination will still work. 
					//if ( !IsPostBack )
					{
						grdMain.DataBind();
					}
				}
			}
			catch(Exception ex)
			{
				SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex);
				lblError.Text = ex.Message;
			}
		}
Exemplo n.º 31
0
        internal static void getRootResource(string fileName, string languageCode, out System.Xml.XmlDocument xmlDocument)
        {
            xmlDocument = null;
            string xmlFilePath = string.Empty;

            if (string.IsNullOrEmpty(languageCode))
            {
                languageCode = commonVariables.SelectedLanguage;
            }
            xmlFilePath = System.Web.HttpContext.Current.Server.MapPath(@"~/App_Data/" + languageCode + @"/" + fileName + ".xml");
            if (System.IO.File.Exists(xmlFilePath))
            {
                xmlDocument = new System.Xml.XmlDocument(); xmlDocument.Load(xmlFilePath);
            }
            else
            {
                xmlFilePath = System.Web.HttpContext.Current.Server.MapPath(@"~/App_Data/en-us/" + fileName + ".xml");
                if (System.IO.File.Exists(xmlFilePath))
                {
                    xmlDocument = new System.Xml.XmlDocument(); xmlDocument.Load(xmlFilePath);
                }
            }
        }
        public static void ConfigureLogFile(string logFileLocation)
        {
            XmlDocument log4netConfig = new System.Xml.XmlDocument();

            log4netConfig.Load(File.OpenRead("log4net.config"));
            var repo = log4net.LogManager.CreateRepository(Assembly.GetEntryAssembly(),
                                                           typeof(log4net.Repository.Hierarchy.Hierarchy));

            log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);

            log4net.Repository.Hierarchy.Hierarchy h =
                (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository(repo.Name.ToString());
            foreach (IAppender a in h.Root.Appenders)
            {
                if (a is FileAppender)
                {
                    FileAppender fa = (FileAppender)a;
                    fa.File = logFileLocation;
                    fa.ActivateOptions();
                    break;
                }
            }
        }
Exemplo n.º 33
0
        /// <summary>
        /// 根据Key修改Value
        /// </summary>
        /// <param name="key">要修改的Key</param>
        /// <param name="value">要修改为的值</param>
        public static void SetValue(string key, string value)
        {
            System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
            xDoc.Load(HttpContext.Current.Server.MapPath("~/XmlConfig/system.config"));
            System.Xml.XmlNode    xNode;
            System.Xml.XmlElement xElem1;
            System.Xml.XmlElement xElem2;
            xNode = xDoc.SelectSingleNode("//appSettings");

            xElem1 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']");
            if (xElem1 != null)
            {
                xElem1.SetAttribute("value", value);
            }
            else
            {
                xElem2 = xDoc.CreateElement("add");
                xElem2.SetAttribute("key", key);
                xElem2.SetAttribute("value", value);
                xNode.AppendChild(xElem2);
            }
            xDoc.Save(HttpContext.Current.Server.MapPath("~/XmlConfig/system.config"));
        }
Exemplo n.º 34
0
 /// <summary>
 /// Cria um nód de com a configuração padrão de Binding.
 /// </summary>
 /// <returns></returns>
 public static ServiceAddressNode CreateDefaultBindingConfiguration()
 {
     using (var sr = new System.IO.StringReader(@"<binding name='WSHttpBinding_IIntegrationService' closeTimeout='00:01:00'
             openTimeout='00:01:00' receiveTimeout='00:10:00' sendTimeout='00:01:00'
             bypassProxyOnLocal='false' transactionFlow='false' hostNameComparisonMode='StrongWildcard'
             maxBufferPoolSize='524288' maxReceivedMessageSize='65536'
             messageEncoding='Text' textEncoding='utf-8' useDefaultWebProxy='true'
             allowCookies='false'>
             <readerQuotas maxDepth='32' maxStringContentLength='8192' maxArrayLength='16384'
                           maxBytesPerRead='4096' maxNameTableCharCount='16384' />
             <reliableSession ordered='true' inactivityTimeout='00:10:00' enabled='false' />
             <security mode='None'>
                 <transport clientCredentialType='None' proxyCredentialType='None' realm='' />
                 <message clientCredentialType='UserName' algorithmSuite='Default' />
             </security>
         </binding>"))
     {
         var xmlReader   = System.Xml.XmlReader.Create(sr);
         var xmlDocument = new System.Xml.XmlDocument();
         xmlDocument.Load(xmlReader);
         return(ServiceAddressNode.CreateFromXmlElement(xmlDocument.DocumentElement));
     }
 }
Exemplo n.º 35
0
        private static Dictionary <string, bool> LoadXML()
        {
            Dictionary <string, bool> _subDic = new Dictionary <string, bool>();

            try
            {
                XmlDocument xmlDoc = new System.Xml.XmlDocument();
                xmlDoc.Load(publishSubscibefile);

                XmlNodeList subservicelist = xmlDoc.DocumentElement.SelectNodes("Subscibe/service");
                foreach (XmlNode xe in subservicelist)
                {
                    _subDic.Add(xe.Attributes["servicename"].Value, xe.Attributes["switch"].Value == "1" ? true : false);
                }
            }
            catch (Exception e)
            {
                MiddlewareLogHelper.WriterLog(LogType.TimingTaskLog, true, System.Drawing.Color.Red, "加载定时任务配置文件错误!");
                MiddlewareLogHelper.WriterLog(LogType.TimingTaskLog, true, System.Drawing.Color.Red, e.Message);
            }

            return(_subDic);
        }
Exemplo n.º 36
0
        bool CheckForExistPersonByName(string name, string surName)
        {
            using (FileStream fStream = new FileStream(Globals.file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                System.Xml.XmlDocument CXML = new System.Xml.XmlDocument();
                CXML.Load(fStream);

                for (int i = 0; i < CXML.DocumentElement.ChildNodes.Count; i++)
                {
                    string fname = String.Format("{0}",
                                                 CXML.DocumentElement.ChildNodes[i].FirstChild.InnerText);
                    string fsurname =
                        CXML.DocumentElement.ChildNodes[i].FirstChild.
                        NextSibling.InnerText;
                    if (name == fname && surName == fsurname)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Exemplo n.º 37
0
        internal static void getLocalResource(string filePath, string languageCode, out System.Xml.XmlDocument xmlDocument)
        {
            xmlDocument = null;

            string filename      = string.Empty;
            string fileDirectory = string.Empty;

            string xmlFilePath = string.Empty;

            if (string.IsNullOrEmpty(filePath))
            {
                filePath = System.Web.HttpContext.Current.Request.CurrentExecutionFilePath;
            }

            filename      = System.IO.Path.GetFileName(filePath);
            fileDirectory = System.Web.HttpContext.Current.Server.MapPath(filePath).Replace(filename, "");

            if (string.IsNullOrEmpty(languageCode))
            {
                languageCode = commonVariables.SelectedLanguage;
            }

            xmlFilePath = fileDirectory + @"App_LocalResources\" + languageCode + @"\" + filename + ".xml";

            if (System.IO.File.Exists(xmlFilePath))
            {
                xmlDocument = new System.Xml.XmlDocument(); xmlDocument.Load(xmlFilePath);
            }
            else
            {
                xmlFilePath = fileDirectory + @"App_LocalResources\en-us\" + filename + ".xml";
                if (System.IO.File.Exists(xmlFilePath))
                {
                    xmlDocument = new System.Xml.XmlDocument(); xmlDocument.Load(xmlFilePath);
                }
            }
        }
Exemplo n.º 38
0
        /// <summary>
        /// Adds an XmlNode to the XmlDocument for the Activity Log.  Gets the
        /// application directory from the registry and then opens or creates
        /// the Activity Log xml file.  Appends the new entry to the XmlDocument
        /// An XmlException is thrown if there is a problem with loading the xml
        /// file.
        /// </summary>
        /// <example>
        /// <code>
        /// CCustSchedItem x = new CCustSchedItem();
        /// x.Event = "Reconfigure Failed";
        /// x.Data = "Custom 1";
        /// x.MeterType = "SENTINEL";
        /// x.UnitID = "Meter ID 1";
        /// x.SerialNumber = "123-456-789";
        ///
        /// x.AddItem();
        /// </code>
        /// </example>
        /// <remarks>
        /// Revision History
        /// MM/DD/YY who Version Issue# Description
        /// -------- --- ------- ------ ---------------------------------------
        /// 07/14/05 rrr 7.13.00 N/A	Creation of class
        /// 04/25/06 mrj 7.30.00        Updated for HH-Pro
        /// 01/15/07 mah 8.00.00 Changed registry access class from CE version
        /// </remarks>
        public void Add()
        {
            //Local variables
            XmlNode xmlnodeRoot;
            XmlNode xmlnodeTemp;
            bool    blnFileCreated = false;

            //Get the data directory for the log and get the log file
            m_strDirectory = CRegistryHelper.GetDataDirectory(m_strApplication);
            blnFileCreated = GetLogFile();

            //Create the xml document and load the xml file if need be
            if (!blnFileCreated)
            {
                m_xmldomLog = new System.Xml.XmlDocument();
                m_xmldomLog.Load(m_strXmlFile);
            }

            //Create the xml node to be added
            ConstructLogItemNode();

            //get the root node to add the xml node to
            xmlnodeRoot = m_xmldomLog.LastChild;
            xmlnodeTemp = xmlnodeRoot;

            //Append the xml node to the root node
            if (null != xmlnodeRoot)
            {
                xmlnodeTemp = xmlnodeRoot.AppendChild(m_xmlnodeLogItem);
            }

            //Save the xml documents and set variables to null
            m_xmldomLog.Save(m_strXmlFile);
            m_xmldomLog = null;
            xmlnodeTemp = null;
            xmlnodeRoot = null;
        }
Exemplo n.º 39
0
        public Game()
        {
            graphics = new GraphicsDeviceManager(this);
            // Initialises the Resolution class, allowing the game to auto-scale all assets based on the resolution.
            Resolution.Init(ref graphics);
            Content.RootDirectory = "Content";

            IsFixedTimeStep = false;

            // Sets up the path to the content folder based on the .exe local location
            _index = Assembly.GetExecutingAssembly().Location.LastIndexOf("\\");
            _path  = Assembly.GetExecutingAssembly().Location.Substring(0, _index);

            // Loads the Application Settings XML file
            System.Xml.XmlDocument appConfigXML = new System.Xml.XmlDocument();
            System.Xml.XmlDocument serConfigXML = new System.Xml.XmlDocument();
            appConfigXML.Load(Game._path + "\\Content\\ApplicationSettings.xml");
            serConfigXML.Load(Game._path + "\\Content\\ServiceSettings.xml");

            // Sets the application settings based on the values of the XML file.
            // Some of the values have to be converted to a different type as when they are read
            // they are all read in as Strings. Of course this then doesn't match the intended type.
            Window.Title = appConfigXML.SelectSingleNode("//ScreenTitle").InnerText;
            int  selectedResolutionWidth  = Convert.ToInt16(appConfigXML.SelectSingleNode("//ScreenWidth").InnerText);
            int  selectedResolutionHeight = Convert.ToInt16(appConfigXML.SelectSingleNode("//ScreenHeight").InnerText);
            bool selectedFullScreen       = Convert.ToBoolean(appConfigXML.SelectSingleNode("//FullScreen").InnerText);

            //bool selectedFullScreen = false;

            // Change Virtual Resolution
            Resolution.SetVirtualResolution(1280, 720); // This is the default resolution.. do not change this or you'll break everything!
            Resolution.SetResolution(selectedResolutionWidth, selectedResolutionHeight, selectedFullScreen);

            screenManager = new ScreenManager(this);
            inputManager  = new InputManager();
            Components.Add(screenManager);
        }
        public static ZaakDocumentAttributes ExtractDocumentAttributes(string zaaktypecode, string documentfilename, string mimetype, DateTime creationdate)
        {
            var result = new ZaakDocumentAttributes();

            result.ZaaktypeCode = zaaktypecode;

            result.Mimetype     = mimetype;
            result.Documenttype = "documenttype";
            result.CreationTime = creationdate;

            result.Taal = "nld";
            result.Vertrouwelijkheid = "VERTROUWELIJK";

            result.Titel        = documentfilename.Contains(".") ? documentfilename.Substring(0, documentfilename.IndexOf(".")) : documentfilename;
            result.Bestandsnaam = documentfilename;
            result.Formaat      = documentfilename.Contains(".") ? documentfilename.Substring(documentfilename.IndexOf(".") + 1) : documentfilename;

            var config = new System.Xml.XmlDocument();

            config.Load("mapping.xml");

            var zaaktypes = config.SelectNodes("//zaaktype");

            foreach (System.Xml.XmlNode zt in zaaktypes)
            {
                if (zt.Attributes["matchfield"] == null ||
                    (zt.Attributes["matchvalue"] != null &&
                     zt.Attributes["matchfield"] != null &&
                     zt.Attributes["matchfield"].Value == "code" &&
                     result.ZaaktypeCode.ToLower().Contains(zt.Attributes["matchvalue"].Value.ToLower())))
                {
                    ChooseDocumentType(zt, result);
                    return(result);
                }
            }
            throw new Exception("Aan het zaaktype met code: " + zaaktypecode + " kunnen geen documenten worden toegevoegd, omdat dit niet is ingesteld");
        }
Exemplo n.º 41
0
 /// <summary>
 /// 客户端版本更新
 /// </summary>
 /// <returns></returns>
 private bool isNewDeviceVersion()
 {
     try
     {
         //版本号更新
         //dynamic servicer = this.Client.Version;//获取当前打包版版本号
         dynamic servicer = this.Client.DeviceVersion;//获取当前版本号
         //获取最新版本号
         System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("ServicerNO.xml");
         System.Xml.XmlDocument   doc    = new System.Xml.XmlDocument();
         doc.Load(reader);
         XmlNode xnode       = doc.DocumentElement.FirstChild;
         string  servicerNew = xnode.Value.ToString();
         //判断当前客户端是否是最新版本,否则更新客户端
         if (string.IsNullOrWhiteSpace(servicerNew) == false)
         {
             System.Version servicerVer = Version.Parse(servicerNew);
             if (this.Client.DeviceVersion < servicerVer)
             {
                 this.Client.ClientUpdate("http://smobiler.com/");
             }
             else
             {
                 return(true);
             }
         }
         else
         {
             return(true);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
     return(false);
 }
Exemplo n.º 42
0
        public bool import(string file)
        {
            bool bok = false;

            XmlDocument doc = new System.Xml.XmlDocument();

            doc.Load(file);
            XmlNode root = findroot(doc.FirstChild);

            if (MessageBox.Show("清空物料基础数据,是否继续?", "提示", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return(false);
            }
            MySqlCommand cmd = Application.instance().myConnection.CreateCommand();

            cmd.CommandText = "delete  from material";
            cmd.ExecuteNonQuery();
            cmd             = Application.instance().myConnection.CreateCommand();
            cmd.CommandText = "delete  from materialcategory";
            cmd.ExecuteNonQuery();

            foreach (XmlNode child in root.ChildNodes)
            {
                string   id       = child.Attributes["ID"].Value;
                string   nodetext = child.Attributes["TEXT"].Value;
                string[] arry     = nodetext.Split('【');
                if (arry.Length == 2)
                {
                    string name = arry[0];
                    string num  = arry[1];
                    num = num.Replace("】", "");
                    loadlevel("-1", "", child);
                }
            }

            return(bok);
        }
Exemplo n.º 43
0
        private void loadPlaylist(string fileName)
        {
            var doc = new System.Xml.XmlDocument();

            doc.Load(fileName);

            var root = doc.DocumentElement;

            mPlaylistListView.SelectedIndex = int.Parse(root.Attributes["IsPlayingAtIndex"].Value);
            _isShuffleEnable = root.Attributes["IsRepeat"].Value == "True" ? true : false;
            _isRepeatEnable  = root.Attributes["IsShuffle"].Value == "True" ? true : false;

            foreach (var song in _playlist)
            {
                _playlist.Remove(song);
            }

            foreach (XmlNode node in root.FirstChild.ChildNodes)
            {
                string song = node.Attributes["Value"].Value;
                _playlist.Add(song);
            }
            mPlaylistListView.ItemsSource = _playlist;
        }
Exemplo n.º 44
0
        public ActionResult InsertNotesInformation()
        {
            if (!Request.IsAuthenticated)
            {
                return RedirectToAction("LogOn", "Account");
            }
            else
            {

                ///Verify if the xml has been updated
                System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(Server.MapPath("/NoteTypes.xml"));
                xtr.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
                System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
                xDoc.Load(xtr);
                var date = xDoc.SelectSingleNode("// types/date[1]/modified").InnerText;

                if (DateTime.Parse(date).AddMonths(int.Parse(System.Configuration.ConfigurationSettings.AppSettings["NoteTypes"])).ToShortDateString() == DateTime.Now.ToShortDateString())
                {
                    Session.Add("createXML", "true");
                }

                return View();
            }
        }
Exemplo n.º 45
0
        private void SetValue(string AppKey, string AppValue)
        {
            System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
            xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");

            System.Xml.XmlNode    xNode;
            System.Xml.XmlElement xElem1;
            System.Xml.XmlElement xElem2;
            xNode = xDoc.SelectSingleNode("//appSettings");

            xElem1 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
            if (xElem1 != null)
            {
                xElem1.SetAttribute("value", AppValue);
            }
            else
            {
                xElem2 = xDoc.CreateElement("add");
                xElem2.SetAttribute("key", AppKey);
                xElem2.SetAttribute("value", AppValue);
                xNode.AppendChild(xElem2);
            }
            xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
        }
Exemplo n.º 46
0
        /// <summary>
        /// Returns the of list of non function properties (nfps) measured for the configurations of the given file. To tune up performance,
        /// we consider only the first configurtion of the file and assume that all configurations have the same nfps.
        /// </summary>
        /// <param name="file">The xml file consisting of configurations.</param>
        /// <returns>The list of nfps the configurations have measurements.</returns>
        public static List <NFProperty> propertiesOfConfigurations(string file)
        {
            List <NFProperty> properties = new List <NFProperty>();

            XmlDocument dat = new System.Xml.XmlDocument();

            dat.Load(file);
            XmlElement currentElemt = dat.DocumentElement;
            XmlNode    node         = currentElemt.ChildNodes[0];

            foreach (XmlNode childNode in node.ChildNodes)
            {
                switch (childNode.Attributes[0].Value)
                {
                // TODO we use this to support result files of the old structure
                case "Configuration":
                    break;

                case "Variable Features":
                    break;


                case "BinaryOptions":
                    break;

                case "NumericOptions":
                    break;

                default:
                    NFProperty property = new NFProperty(childNode.Attributes[0].Value);
                    properties.Add(property);
                    break;
                }
            }
            return(properties);
        }
Exemplo n.º 47
0
        /// <summary>
        /// 获取指定预约工作站的名称
        /// </summary>
        /// <param name="p_strStationType"></param>
        /// <returns></returns>
        public static string s_strGetStationName(int p_strStationType)
        {
            if (s_hasStationName == null)
            {
                try
                {
                    System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();

                    string [] strFilePathAll    = Application.ExecutablePath.Split('\\');
                    string    strFilePathHeader = "";
                    if (strFilePathAll != null)
                    {
                        for (int i = 0; i < strFilePathAll.Length - 3; i++)
                        {
                            strFilePathHeader += strFilePathAll[i] + "\\\\";
                        }
                    }
                    string strStationXml = strFilePathHeader + "Templates\\\\PACSStation.xml";

                    xmlDoc.Load(strStationXml);

                    s_hasStationName = new Hashtable();

                    foreach (XmlNode xndStationName in xmlDoc.DocumentElement.ChildNodes)
                    {
                        s_hasStationName.Add(xndStationName.Attributes["TYPEID"].Value, xndStationName.Attributes["NAME"].Value);
                    }
                }
                catch
                {
                    return("");
                }
            }

            return((string)s_hasStationName[p_strStationType.ToString()]);
        }
Exemplo n.º 48
0
        //no use
        public XmlNode GetParameterForJava(Session session, string companyCode, string version)
        {
            //Get xml
            try
            {
                string physicalPath = SettingManager.Default.PhysicPath + "\\" + companyCode + "\\" + version + "\\";
                string xmlPath      = physicalPath + "Setting\\Parameter.xml";
                var    doc          = new System.Xml.XmlDocument();
                doc.Load(xmlPath);
                xmlPath = physicalPath + "Setting\\Login.xml";
                var doc2 = new System.Xml.XmlDocument();
                doc2.Load(xmlPath);
                var node2 = doc2.GetElementsByTagName("Login")[0];

                var parameterXmlNode = doc.GetElementsByTagName("Parameter")[0];

                string      newsLanguage = node2.SelectNodes("NewsLanguage").Item(0).InnerXml;
                TraderState state        = SessionManager.Default.GetTradingConsoleState(session);
                if (state == null)
                {
                    state = new TraderState(session.ToString());
                }
                state.Language = newsLanguage.ToLower();
                SessionManager.Default.AddTradingConsoleState(session, state);
                XmlElement newChild = doc.CreateElement("NewsLanguage");
                newChild.InnerText = newsLanguage;
                parameterXmlNode.AppendChild(newChild);
                var node = doc.GetElementsByTagName("Parameters")[0];
                return(node);
            }
            catch (System.Exception ex)
            {
                _Logger.Error(ex);
                return(null);
            }
        }
Exemplo n.º 49
0
        static void Main(string[] args)
        {
            var file = args[0];

            if (!File.Exists(file))
            {
                throw new FileNotFoundException(string.Format("File not found! : {0}", file));
            }

            System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();
            xdoc.Load(file);
            System.Text.StringBuilder b = new System.Text.StringBuilder();
            GetConnections(b, xdoc.SelectNodes("/Connections/Node"));
            var outputFileName = Path.Combine(new FileInfo(file).Directory.FullName, "mRemoteNGConnections.txt");

            if (File.Exists(outputFileName))
            {
                File.Delete(outputFileName);
            }
            using (StreamWriter writer = new StreamWriter(outputFileName))
            {
                writer.Write(b.ToString());
            }
        }
Exemplo n.º 50
0
        public static void Clean(string fileName)
        {
            System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();

            if (FileManager.IsRelative(fileName))
            {
                fileName = FileManager.MakeAbsolute(fileName);
            }
            xmlDocument.Load(fileName);

            XmlNode sceneNode = xmlDocument.ChildNodes[1];

            foreach (XmlNode child in sceneNode)
            {
                switch (child.Name)
                {
                case "Sprite":
                    GeneralCleaner.CleanNode(child, SpriteSave, SpriteSaveType);
                    break;

                case "Camera":
                    GeneralCleaner.CleanNode(child, CameraSave, CameraSaveType);
                    break;

                case "SpriteFrame":
                    GeneralCleaner.CleanNode(child, SpriteFrameSave, SpriteFrameSaveType);
                    break;

                case "Text":
                    GeneralCleaner.CleanNode(child, TextSave, TextSaveType);
                    break;
                }
            }

            xmlDocument.Save(fileName);
        }
Exemplo n.º 51
0
        public string Read(string Key)
        {
            string str = "";

            // use reflection to find the location of the config file
            System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
            System.IO.FileInfo         fi  = new System.IO.FileInfo(String.Format("{0}.config", asm.Location));

            if (!fi.Exists)
            {
                throw new Exception("Missing config file");
            }

            // load the config file into the XML DOM.
            System.Xml.XmlDocument xmlConfig = new System.Xml.XmlDocument();
            xmlConfig.PreserveWhitespace = true;

            xmlConfig.Load(fi.FullName);

            // find the right node and change it to the new value
            foreach (System.Xml.XmlNode node in     xmlConfig["configuration"]["appSettings"])
            {
                if ((node.Name == "add") &&
                    (node.Attributes.GetNamedItem("key").Value ==
                     Key))
                {
                    str = (node.Attributes.GetNamedItem("value").Value);
                    break;
                    //Trace.Write("name" + node.Name);
                }
            }


            return(str);
            //xmlConfig.Save (fi.FullName);
        }
Exemplo n.º 52
0
        internal static void getLocalResource(out System.Xml.XmlDocument xmlDocument)
        {
            xmlDocument = null;
            string filePath     = string.Empty;
            string languageCode = string.Empty;
            string xmlFilePath  = string.Empty;

            filePath     = System.Web.HttpContext.Current.Request.CurrentExecutionFilePath;
            languageCode = commonVariables.SelectedLanguage;
            xmlFilePath  = System.Web.HttpContext.Current.Server.MapPath(@"~/App_Data/" + languageCode + @"/" + filePath + ".xml");

            if (System.IO.File.Exists(xmlFilePath))
            {
                xmlDocument = new System.Xml.XmlDocument(); xmlDocument.Load(xmlFilePath);
            }
            else
            {
                xmlFilePath = System.Web.HttpContext.Current.Server.MapPath(@"~/App_Data/en-us/" + filePath + ".xml");
                if (System.IO.File.Exists(xmlFilePath))
                {
                    xmlDocument = new System.Xml.XmlDocument(); xmlDocument.Load(xmlFilePath);
                }
            }
        }
Exemplo n.º 53
0
        public static void Load()
        {
            string path = SettingsPath;

            try
            {
                if (!System.IO.File.Exists(path))
                {
                    path = Path.Combine(System.Windows.Forms.Application.StartupPath, "Settings.xml");
                }
                System.Xml.XmlDocument Xml = new System.Xml.XmlDocument();

                Xml.Load(path);

                gtop    = ColorTranslator.FromHtml(Xml["Settings"]["GradientTop"].InnerText);
                gbottom = ColorTranslator.FromHtml(Xml["Settings"]["GradientBottom"].InnerText);
                ol      = ColorTranslator.FromHtml(Xml["Settings"]["OutlineColor"].InnerText);
                text    = ColorTranslator.FromHtml(Xml["Settings"]["TextColor"].InnerText);
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message, "An Error Occured");
            }
        }
Exemplo n.º 54
0
        Stream ChangeMargins(Stream xmlStream, double PrescriptionWidth, double PrescriptionHeight, double LeftMargin, double TopMargin)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(xmlStream);
            xmlStream.Close();
            XmlNode report = doc.SelectSingleNode("./*");

            foreach (XmlNode node in report.ChildNodes)
            {
                if (node.Name == "LeftMargin")
                {
                    node.InnerText = LeftMargin.ToString().Replace(",", ".") + "mm";
                }

                if (node.Name == "TopMargin")
                {
                    node.InnerText = TopMargin.ToString().Replace(",", ".") + "mm";
                }

                if (node.Name == "PageWidth")
                {
                    node.InnerText = (PrescriptionWidth * 10.0 + LeftMargin).ToString().Replace(",", ".") + "mm";
                }

                if (node.Name == "PageHeight")
                {
                    node.InnerText = (PrescriptionHeight * 10.0 + TopMargin).ToString().Replace(",", ".") + "mm";
                }
            }
            MemoryStream stream = new
                                  MemoryStream(); doc.Save(stream);

            stream.Seek(0, SeekOrigin.Begin);

            return(stream);
        }
Exemplo n.º 55
0
        private void Frm_UpdateDialog_Load(object sender, EventArgs e)
        {
            m_pDbManager      = new CDbManager_Sqlite(Application.StartupPath + "\\rainfall.sqlite", "");
            m_pDbTempManager  = new CDbManager_Sqlite(Application.StartupPath + "\\temp.sqlite", "");
            CSQLite.G_CSQLite = new CSQLite(m_pDbManager, m_pDbTempManager);

            XmlDocument doc = new System.Xml.XmlDocument();

            doc.Load(AppDomain.CurrentDomain.BaseDirectory + "Update.xml");
            XmlNodeList pList = doc.SelectNodes("/update/fileList/file");

            int i = 0;

            foreach (XmlNode nl in pList)
            {
                this.lbMsg.Items.Add(nl.Attributes[0].Value);
                i++;
            }
            this.txtCaption.Text = string.Format("检测到{0}个更新文件,单击安装完成更新!", i);
            if (i == 0)
            {
                this.txtCaption.Text = string.Format("检测到新的配置文件,单击安装完成更新!", i);
            }
        }
Exemplo n.º 56
0
        /// <summary>
        /// private implementation to load the data from the source.
        /// </summary>
        /// <param name="sourcepath"></param>
        /// <returns></returns>
        private System.Xml.XmlDocument LoadXMLDocument(string sourcepath, PDFDataContext context)
        {
            if (string.IsNullOrEmpty(sourcepath))
            {
                throw new ArgumentNullException(string.Format(Errors.NoSourcePathDefinedOnXmlDataSource, this.ID));
            }


            Document pdf  = this.Document;
            string   path = this.MapPath(sourcepath);

            System.Xml.XmlDocument doc = null;

            try
            {
                doc = new System.Xml.XmlDocument();
                doc.Load(path);
            }
            catch (Exception ex)
            {
                throw new PDFDataException(string.Format(Errors.CouldNotLoadTheDataFromTheSourcePath, "XML", sourcepath), ex);
            }
            return(doc);
        }
Exemplo n.º 57
0
        public Settings(String flname)
        {
            System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
            xml.Load(flname);
            rdir = "";
            udir = "";
            idir = "";

            ftpu = "";
            ftpd = "";
            ftpp = "";
            ftps = "";

            autoletter = false;

            XmlNode n = xml.FirstChild;

            StartParsing(n);

            if (udir == "")
            {
                udir = rdir;
            }
        }
Exemplo n.º 58
0
        public string BuildNFinal(string projectFile, string versionText)
        {
            string projectRoot   = Path.GetDirectoryName(projectFile) + "\\";
            string webconfigFile = projectRoot + "Web.config";

            System.Xml.XmlDocument xmlConfig = new System.Xml.XmlDocument();
            string[] Apps = null;
            if (File.Exists(webconfigFile))
            {
                xmlConfig.Load(webconfigFile);
                XmlNode appsNode = xmlConfig.DocumentElement.SelectSingleNode("appSettings/add[@key='Apps']");
                if (appsNode != null && appsNode.Attributes.Count > 0 && appsNode.Attributes["value"] != null)
                {
                    Apps = appsNode.Attributes["value"].Value.Split(',');
                }
            }
            if (Apps == null)
            {
                return("Web.config中找不到app配置项");
            }
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(projectFile);
            string nameSpace = doc.DocumentElement.Attributes["xmlns"].Value;
            XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable);

            namespaceManager.AddNamespace("x", nameSpace);
            Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version;
            //如果versionText不存在就取工程文件中的版本
            if (string.IsNullOrEmpty(versionText))
            {
                XmlNode versionNode = doc.DocumentElement.SelectSingleNode("x:PropertyGroup/x:TargetFrameworkVersion", namespaceManager);
                versionText = versionNode.InnerText;
            }
            switch (versionText)
            {
            case "v1.1": version = Microsoft.Build.Utilities.TargetDotNetFrameworkVersion.Version11; break;

            case "v2.0": version = Microsoft.Build.Utilities.TargetDotNetFrameworkVersion.Version20; break;

            case "v3.0": version = Microsoft.Build.Utilities.TargetDotNetFrameworkVersion.Version30; break;

            case "v3.5": version = Microsoft.Build.Utilities.TargetDotNetFrameworkVersion.Version35; break;

            case "v4.0": version = Microsoft.Build.Utilities.TargetDotNetFrameworkVersion.Version40; break;

            //case "v4.5": version = Microsoft.Build.Utilities.TargetDotNetFrameworkVersion.Version45; break;
            default: version = Microsoft.Build.Utilities.TargetDotNetFrameworkVersion.VersionLatest; break;
            }
            bool          supportOracle  = false;
            bool          isNet2         = false;
            List <string> references     = new List <string>();
            XmlNodeList   referenceNodes = doc.DocumentElement.SelectNodes("x:ItemGroup/x:Reference[@Include]", namespaceManager);
            XmlNode       hintPathNode   = null;
            string        dllPath        = null;
            string        referencePath  = null; //= Microsoft.Build.Utilities.ToolLocationHelper.GetPathToDotNetFrameworkReferenceAssemblies(version);
            string        frameworkPath  = null; // Microsoft.Build.Utilities.ToolLocationHelper.GetPathToDotNetFramework(version);

            ///reference:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\mscorlib.dll"

            ///reference:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Core.dll"

            if (version == Microsoft.Build.Utilities.TargetDotNetFrameworkVersion.Version11 ||
                version == Microsoft.Build.Utilities.TargetDotNetFrameworkVersion.Version20 ||
                version == Microsoft.Build.Utilities.TargetDotNetFrameworkVersion.Version30 ||
                version == Microsoft.Build.Utilities.TargetDotNetFrameworkVersion.Version35)
            {
                supportOracle = false;
                isNet2        = true;
                referencePath = Microsoft.Build.Utilities.ToolLocationHelper.GetPathToDotNetFramework(
                    Microsoft.Build.Utilities.TargetDotNetFrameworkVersion.Version20);
                frameworkPath = Microsoft.Build.Utilities.ToolLocationHelper.GetPathToDotNetFramework(version);
                references.Add(Path.Combine(Microsoft.Build.Utilities.ToolLocationHelper.GetPathToDotNetFramework(
                                                Microsoft.Build.Utilities.TargetDotNetFrameworkVersion.Version20), "mscorlib.dll"));
            }
            else
            {
                referencePath = Microsoft.Build.Utilities.ToolLocationHelper.GetPathToDotNetFrameworkReferenceAssemblies(version);
                frameworkPath = Microsoft.Build.Utilities.ToolLocationHelper.GetPathToDotNetFramework(version);
                references.Add(Path.Combine(referencePath, "mscorlib.dll"));
                references.Add(Path.Combine(referencePath, "System.Core.dll"));
                supportOracle = true;
                isNet2        = false;
            }

            for (int i = 0; i < referenceNodes.Count; i++)
            {
                hintPathNode = referenceNodes[i].SelectSingleNode("x:HintPath", namespaceManager);

                //引入
                //如果是.net内部的dll文件
                if (hintPathNode == null)
                {
                    dllPath = Path.Combine(referencePath, referenceNodes[i].Attributes["Include"].Value.Split(',')[0] + ".dll");
                    if (File.Exists(dllPath))
                    {
                        references.Add(dllPath);
                    }
                }
                //如果是外部引用
                else
                {
                    dllPath = Path.Combine(projectRoot + "bin\\", Path.GetFileName(hintPathNode.InnerText));

                    //如果是oracle这个dll,则要看是否支持来引入
                    if (Path.GetFileName(dllPath) == "Oracle.ManagedDataAccess.dll")
                    {
                        if (!supportOracle)
                        {
                            if (File.Exists(dllPath))
                            {
                                File.Delete(dllPath);
                            }
                            //如果不支持oracle则直接跳过,不引入该dll文件
                            continue;
                        }
                        else
                        {
                            if (!File.Exists(dllPath))
                            {
                                dllPath = projectRoot + "NFinal\\Resource\\Oracle.ManagedDataAccess.dll";
                            }
                        }
                    }
                    references.Add(dllPath);
                }
            }
            string cscExeFileName = null;

            if (isNet2)
            {
                cscExeFileName = Path.Combine(Microsoft.Build.Utilities.ToolLocationHelper.GetPathToDotNetFramework(
                                                  Microsoft.Build.Utilities.TargetDotNetFrameworkVersion.Version35), "csc.exe");
            }
            else
            {
                cscExeFileName = Path.Combine(frameworkPath, "csc.exe");
            }
            StringBuilder commandText = new StringBuilder();
            //cs0472,由于“decimal”类型的值永不等于“decimal?”类型的“null”,该表达式的结果始终为“false”
            //0219,warning CS0219: 变量“a”已赋值,但其值从未使用过
            //如果不支持oracle则不编译oracle相关代码
            StringBuilder Def = new StringBuilder();

            if (supportOracle)
            {
                Def.Append(";ORACLE");
            }
            if (isNet2)
            {
                Def.Append(";NET2");
            }
            commandText.Append(string.Format("/noconfig /unsafe+ /nowarn:0219,1701,1702,0472 /nostdlib+ /errorreport:prompt /warn:4 /define:TRACE{0} ", Def.ToString()));
            for (int i = 0; i < references.Count; i++)
            {
                commandText.Append(string.Format("/reference:\"{0}\" ", references[i]));
            }
            commandText.Append(string.Format("/debug:pdbonly /optimize- /out:\"{0}obj\\Release\\WebMvc.dll\" ", projectRoot));
            commandText.Append("/target:library /utf8output ");
            //if(version==Microsoft.Build.Utilities.TargetDotNetFrameworkVersion.Version40)
            //{
            //    commandText.Append(string.Format("\"{0}\" ",Path.Combine(projectRoot,"NFinal\\Compile\\Build\\.NETFramework,Version=v4.0.AssemblyAttributes.txt")));
            //}
            //else if(version==Microsoft.Build.Utilities.TargetDotNetFrameworkVersion.Version45)
            //{
            //    commandText.Append(string.Format("\"{0}\" ", Path.Combine(projectRoot, "NFinal\\Compile\\Build\\.NETFramework,Version=v4.5.AssemblyAttributes.txt")));
            //}
            //else if(version==Microsoft.Build.Utilities.TargetDotNetFrameworkVersion.VersionLatest)
            //{

            //    commandText.Append(string.Format("\"{0}\" ",Path.Combine(projectRoot,"NFinal\\Compile\\Build\\.NETFramework,Version=v4.5.1.AssemblyAttributes.txt")));
            //}

            //添加App下的代码
            for (int i = 0; i < Apps.Length; i++)
            {
                string[] webFileNames = Directory.GetFiles(projectRoot + Apps[i] + "\\Web\\", "*.cs", SearchOption.AllDirectories);
                AddFiles(ref commandText, webFileNames);
                string[] classFileNames = Directory.GetFiles(projectRoot + Apps[i] + "\\Common\\", "*.cs", SearchOption.AllDirectories);
                AddFiles(ref commandText, classFileNames);
                string[] conentFileNames = Directory.GetFiles(projectRoot + Apps[i] + "\\Content\\", "*.cs", SearchOption.AllDirectories);
                AddFiles(ref commandText, conentFileNames);
                string[] dalFileNames = Directory.GetFiles(projectRoot + Apps[i] + "\\Models\\DAL\\", "*.cs", SearchOption.AllDirectories);
                AddFiles(ref commandText, dalFileNames);
                //string[] dbFileNames = Directory.GetFiles(projectRoot + Apps[i] + "\\Models\\", "*.cs", SearchOption.TopDirectoryOnly);
                //AddFiles(ref commandText, dbFileNames);
                string[] appFiles = new string[] {
                    projectRoot + Apps[i] + "\\Models\\ConnectionStrings.cs",
                    projectRoot + Apps[i] + "\\Router.cs",
                    projectRoot + Apps[i] + "\\Config.cs",
                    projectRoot + Apps[i] + "\\Extension.cs",
                    projectRoot + Apps[i] + "\\WebCompiler.aspx.cs",
                    projectRoot + Apps[i] + "\\WebCompiler.aspx.designer.cs"
                };
                AddFiles(ref commandText, appFiles);
            }
            //添加所有的NFinal下的代码
            bool buildAll = true;

            if (buildAll)
            {
                string[] NFinalCompiles = Directory.GetFiles(projectRoot + "NFinal\\Compile\\", "*.cs", SearchOption.AllDirectories);
                AddFiles(ref commandText, NFinalCompiles);
                string[] NFinalDBCodings = Directory.GetFiles(projectRoot + "NFinal\\DB\\Coding\\", "*.cs", SearchOption.AllDirectories);
                AddFiles(ref commandText, NFinalDBCodings);
                string[] NFinalVTemplates = Directory.GetFiles(projectRoot + "NFinal\\VTemplate\\", "*.cs", SearchOption.AllDirectories);
                AddFiles(ref commandText, NFinalVTemplates);
                string[] NFinalCommons = Directory.GetFiles(projectRoot + "NFinal\\Common\\", "*.cs", SearchOption.AllDirectories);
                AddFiles(ref commandText, NFinalCommons);
                string[] NFinalTemplate = Directory.GetFiles(projectRoot + "NFinal\\Template\\", "*.cs", SearchOption.AllDirectories);
                AddFiles(ref commandText, NFinalTemplate);
                //string[] NFinalControlls = Directory.GetFiles(projectFile +"NFinal\\Controll\\","*.cs",SearchOption.AllDirectories);
                //AddFiles(ref commandText,NFinalControlls);
                //string[] NFinalContents = Directory.GetFiles(projectFile+"NFinal\\Content\\","*.cs",SearchOption.AllDirectories);
                //AddFiles(ref commandText,NFinalContents);
                //添加NFinal下的代码
                string[] nfDbFileNames = new string[] {
                    projectRoot + "NFinal\\Application.cs",
                    projectRoot + "NFinal\\Config.cs",
                    projectRoot + "NFinal\\Frame.cs",
                    projectRoot + "NFinal\\Builder.cs",
                    projectRoot + "NFinal\\DB\\SqlObject.cs",
                    projectRoot + "NFinal\\DB\\NList.cs",
                    projectRoot + "NFinal\\DB\\NStruct.txt",
                    projectRoot + "NFinal\\DB\\DBType.cs",
                    projectRoot + "NFinal\\DB\\ConnectionString.cs",
                    projectRoot + "NFinal\\Session\\Session.cs",
                    projectRoot + "NFinal\\Handler\\Handler.cs",
                    projectRoot + "NFinal\\Handler\\HandlerFactory.cs",
                    projectRoot + "NFinal\\Handler\\HttpAsyncHandler.cs",
                    projectRoot + "NFinal\\BaseAction.cs",
                    projectRoot + "NFinal\\Main.cs",
                    projectRoot + "NFinal\\Resource\\fileTree\\connectors\\editor.ashx.cs",
                    projectRoot + "NFinal\\Resource\\fileTree\\connectors\\jqueryFileTree.ashx.cs"
                };
                AddFiles(ref commandText, nfDbFileNames);
            }
            else
            {
                //添加NFinal下的代码
                string[] nfDbFileNames = new string[] {
                    projectRoot + "NFinal\\DB\\SqlObject.cs",
                    projectRoot + "NFinal\\DB\\NList.cs",
                    projectRoot + "NFinal\\DB\\NStruct.txt",
                    projectRoot + "NFinal\\Session\\Session.cs",
                    projectRoot + "NFinal\\Handler\\Handler.cs",
                    projectRoot + "NFinal\\Handler\\HandlerFactory.cs",
                    projectRoot + "NFinal\\Handler\\HttpAsyncHandler.cs",
                    projectRoot + "NFinal\\BaseAction.cs",
                    projectRoot + "NFinal\\Main.cs",
                    projectRoot + "NFinal\\Resource\\fileTree\\connectors\\editor.ashx.cs",
                    projectRoot + "NFinal\\Resource\\fileTree\\connectors\\jqueryFileTree.ashx.cs"
                };
                AddFiles(ref commandText, nfDbFileNames);
            }
            //urlRewriter
            string[] urlRewriterFileNames = Directory.GetFiles(projectRoot + "NFinal\\UrlRewriter\\", "*.cs", SearchOption.AllDirectories);
            AddFiles(ref commandText, urlRewriterFileNames);
            //litJson
            string[] litJsonFileNames = Directory.GetFiles(projectRoot + "NFinal\\LitJson\\", "*.cs", SearchOption.AllDirectories);
            AddFiles(ref commandText, litJsonFileNames);

            string propertyFileName = Path.Combine(projectRoot, "Properties\\Settings.Designer.cs");

            if (File.Exists(propertyFileName))
            {
                commandText.Append(string.Format("\"{0}\" ", propertyFileName));
            }
            propertyFileName = Path.Combine(projectRoot, "Properties\\AssemblyInfo.cs");
            if (File.Exists(propertyFileName))
            {
                commandText.Append(string.Format("\"{0}\" ", propertyFileName));
            }
            string commandLine = commandText.ToString();

            return(ExeCommand(cscExeFileName, commandLine));
        }
        public void Load()
        {
            var dom = new System.Xml.XmlDocument();

            dom.Load(_fileName);

            var root = dom.DocumentElement;

            _randomize = Convert.ToBoolean(root.SelectSingleNode("/Simulation/GlobalParameters/Randomize").InnerText);

            if (root.SelectSingleNode("/Simulation/GlobalParameters/RandomNumberGenerator") != null)
            {
                var rngAsString = root.SelectSingleNode("/Simulation/GlobalParameters/RandomNumberGenerator").InnerText.ToLowerInvariant();

                switch (rngAsString)
                {
                case "dotnet": _rng = RandomNumberGenerator.DotNet; break;

                case "mersennetwister": _rng = RandomNumberGenerator.MersenneTwister; break;

                default: throw new InvalidOperationException("The configuration value for the RandomNumberGenerator is not supported");
                }
            }
            else
            {
                _rng = RandomNumberGenerator.DotNet;
            }

            var defaultYearsToAggregate     = Convert.ToInt32(root.SelectSingleNode("/Simulation/GlobalParameters/YearsToAggregate").InnerText);
            var defaultOutputDisaggregated  = Convert.ToBoolean(root.SelectSingleNode("/Simulation/GlobalParameters/OutputDisaggregatedData").InnerText);
            var defaultWeightingCombination = root.SelectSingleNode("/Simulation/GlobalParameters/WeightingCombination").InnerText;
            var defaultMonteCarloRuns       = Convert.ToInt32(root.SelectSingleNode("/Simulation/GlobalParameters/MonteCarloRuns").InnerText);

            _outputVerbal          = Convert.ToBoolean(root.SelectSingleNode("/Simulation/GlobalParameters/OutputVerbal").InnerText);
            _outputInputParameters = Convert.ToBoolean(root.SelectSingleNode("/Simulation/GlobalParameters/OutputInputParameters").InnerText);

            if (root.SelectSingleNode("/Simulation/GlobalParameters/SameRandomStreamPerRun") != null)
            {
                SameRandomStreamPerRun = Convert.ToBoolean(root.SelectSingleNode("/Simulation/GlobalParameters/SameRandomStreamPerRun").InnerText);
            }
            else
            {
                SameRandomStreamPerRun = false;
            }

            if (root.SelectSingleNode("/Simulation/GlobalParameters/RunParallel") != null)
            {
                RunParallel = Convert.ToBoolean(root.SelectSingleNode("/Simulation/GlobalParameters/RunParallel").InnerText);
            }
            else
            {
                RunParallel = false;
            }

            var scenarioNodes = root.SelectNodes("/Simulation/Scenarios/Scenario");
            var lScenarios    = new Dictionary <string, Scenario>();

            var currentScenarioId = 0;

            foreach (XmlNode scenarioNode in scenarioNodes)
            {
                var scenario = new Scenario();
                scenario.Name = (scenarioNode as XmlElement).GetAttribute("name");
                scenario.Id   = currentScenarioId;

                var excelfileNodes = scenarioNode.SelectNodes("ExcelFile");
                foreach (XmlNode excelfileNode in excelfileNodes)
                {
                    string excelfilename = Path.IsPathRooted(excelfileNode.InnerText) ? excelfileNode.InnerText : Path.Combine(Path.GetDirectoryName(Path.GetFullPath(_fileName)), excelfileNode.InnerText);
                    scenario.ExcelFiles.Add(excelfilename);
                }

                lScenarios.Add(scenario.Name, scenario);
                _scenarios.Add(scenario);

                currentScenarioId++;
            }

            var runNodes = root.SelectNodes("/Simulation/Runs/Run");

            foreach (XmlNode runNode in runNodes)
            {
                var run = new Run();

                run.Scenario = lScenarios[runNode.SelectSingleNode("Scenario").InnerText];

                if (runNode.SelectSingleNode("MonteCarloRuns") != null)
                {
                    run.MonteCarloRuns = Convert.ToInt32(runNode.SelectSingleNode("MonteCarloRuns").InnerText);
                }
                else
                {
                    run.MonteCarloRuns = defaultMonteCarloRuns;
                }

                switch (runNode.SelectSingleNode("Mode").InnerText)
                {
                case "Marginal": run.Mode = RunMode.MarginalRun; break;

                case "Total": run.Mode = RunMode.TotalRun; break;

                case "FullMarginal": run.Mode = RunMode.FullMarginalRun; break;

                default: throw new ApplicationException("Invalid value for Mode in configuration file");
                }

                if (runNode.SelectSingleNode("YearsToAggregate") != null)
                {
                    run.YearsToAggregate = Convert.ToInt32(runNode.SelectSingleNode("YearsToAggregate").InnerText);
                }
                else
                {
                    run.YearsToAggregate = defaultYearsToAggregate;
                }

                if (runNode.SelectSingleNode("CalculateMeanForMonteCarlo") != null)
                {
                    run.CalculateMeanForMonteCarlo = Convert.ToBoolean(runNode.SelectSingleNode("CalculateMeanForMonteCarlo").InnerText);
                }
                else
                {
                    run.CalculateMeanForMonteCarlo = false;
                }

                if (runNode.SelectSingleNode("OutputAllMonteCarloRuns") != null)
                {
                    run.OutputAllMonteCarloRuns = Convert.ToBoolean(runNode.SelectSingleNode("OutputAllMonteCarloRuns").InnerText);
                }
                else
                {
                    run.OutputAllMonteCarloRuns = true;
                }

                if (runNode.SelectSingleNode("WeightingCombination") != null)
                {
                    run.WeightingCombination = runNode.SelectSingleNode("WeightingCombination").InnerText;
                }
                else
                {
                    run.WeightingCombination = defaultWeightingCombination;
                }

                if (runNode.SelectSingleNode("OutputDisaggregatedData") != null)
                {
                    run.OutputDisaggregatedData = Convert.ToBoolean(runNode.SelectSingleNode("OutputDisaggregatedData").InnerText);
                }
                else
                {
                    run.OutputDisaggregatedData = defaultOutputDisaggregated;
                }

                if (runNode.SelectSingleNode("EmissionYear") != null)
                {
                    run.EmissionYear = Timestep.FromYear(Convert.ToInt32(runNode.SelectSingleNode("EmissionYear").InnerText));
                }
                else
                {
                    run.EmissionYear = Timestep.FromYear(2005);
                }

                if (runNode.SelectSingleNode("MarginalGas") != null)
                {
                    switch (runNode.SelectSingleNode("MarginalGas").InnerText)
                    {
                    case "C": run.MarginalGas = MarginalGas.C; break;

                    case "CH4": run.MarginalGas = MarginalGas.CH4; break;

                    case "N2O": run.MarginalGas = MarginalGas.N2O; break;

                    case "SF6": run.MarginalGas = MarginalGas.SF6; break;

                    default: throw new ApplicationException("Invalid value for MarginalGas in configuration file");
                    }
                }
                else
                {
                    run.MarginalGas = MarginalGas.C;
                }

                if (runNode.SelectSingleNode("InitialTax") != null)
                {
                    run.InitialTax = Convert.ToDouble(runNode.SelectSingleNode("InitialTax").InnerText);
                }
                else
                {
                    run.InitialTax = 0.0;
                }

                run.OutputVerbal = _outputVerbal;

                _runs.Add(run);
            }
        }
Exemplo n.º 60
0
        public override void OpenFile(object sender, EventArgs e)
        {
            if (xmlHasChanged)
            {
                SaveXml(true);
            }
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            openFileDialog.Filter           = "TVM Files (*.tvm)|*.tvm|CFLO Files (*.cfo)|*.cfo|All Files (*.*)|*.*";
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                try
                {
                    xmlFilename   = openFileDialog.FileName;
                    xmlHasChanged = true;
                    doc.Load(xmlFilename);
                    XmlNode     root        = doc.DocumentElement;
                    XmlNodeList fa_tvm_n    = doc.GetElementsByTagName("N");
                    XmlNodeList fa_tvm_pv   = doc.GetElementsByTagName("PV");
                    XmlNodeList fa_tvm_pmt  = doc.GetElementsByTagName("PMT");
                    XmlNodeList fa_tvm_fv   = doc.GetElementsByTagName("FV");
                    XmlNodeList fa_tvm_i    = doc.GetElementsByTagName("I");
                    XmlNodeList fa_tvm_p    = doc.GetElementsByTagName("P");
                    XmlNodeList fa_tvm_from = doc.GetElementsByTagName("FROM");
                    XmlNodeList fa_tvm_to   = doc.GetElementsByTagName("TO");

                    textBoxN.Text = fa_tvm_n[0].InnerText;
                    XmlAttribute isYearatt = doc.GetElementsByTagName("N")[0].Attributes[0];
                    if (isYearatt.InnerText == "true")
                    {
                        radioButtonYears.Checked   = true;
                        radioButtonPeriods.Checked = false;
                        isYear = true;
                    }
                    else
                    {
                        radioButtonPeriods.Checked = true;
                        radioButtonYears.Checked   = false;
                        isYear = false;
                    }
                    textBoxPV.Text  = fa_tvm_pv[0].InnerText;
                    textBoxPMT.Text = fa_tvm_pmt[0].InnerText;
                    textBoxFV.Text  = fa_tvm_fv[0].InnerText;
                    textBoxI.Text   = fa_tvm_i[0].InnerText;
                    textBoxP.Text   = fa_tvm_p[0].InnerText;
                    XmlAttribute isEndatt = doc.GetElementsByTagName("P")[0].Attributes[0];
                    if (isEndatt.InnerText == "true")
                    {
                        radioButtonEnd.Checked   = true;
                        radioButtonBegin.Checked = false;
                    }
                    else
                    {
                        radioButtonBegin.Checked = true;
                        radioButtonEnd.Checked   = false;
                    }
                    // * IMPORTANT * must set the To value before From value
                    //   because of event handler checking for correct From to To value
                    numericUpDownTo.Value   = decimal.Parse(fa_tvm_to[0].InnerText);
                    numericUpDownFrom.Value = decimal.Parse(fa_tvm_from[0].InnerText);
                    tvm.setCalculating(TVMObjects.OPEN);
                    recalc(TVMObjects.OPEN);

                    /*
                     * Sample tvm file for loading
                     *
                     * <?xml version="1.0" encoding="utf-16"?>
                     * <FA>
                     *  <TVM>
                     *      <N isYear="true">30.00</N>
                     *      <PV>$300,000.00</PV>
                     *      <PMT>($1,798.65)</PMT>
                     *      <FV>$0.00</FV>
                     *      <I>6.00</I>
                     *      <P isEnd="true">12</P>
                     *      <FROM>1</FROM>
                     *      <TO>12</TO>
                     *  </TVM>
                     * </FA>
                     * */
                    this.Text     = formTitle + " - " + xmlFilename;
                    xmlHasChanged = false;
                }
                catch (XmlException)
                {
                    MessageBox.Show("Invalid file.\nThe file you have opened is not valid for this application.", "Invalid file");
                }
                catch (NullReferenceException)
                {
                    MessageBox.Show("Incomplete file.\nThe file you have opened is not valid for this application.", "Invalid file");
                }
                catch (ArgumentOutOfRangeException)
                {
                    MessageBox.Show("Value is out of range.\nThe file you have opened is not valid for this application.", "Invalid file");
                }
            }
        }