MoveToElement() public method

public MoveToElement ( ) : bool
return bool
        private static volatile Dictionary<String, Individual> _users; // = new Dictionary<string, Individual>();

        #endregion Fields

        #region Constructors

        private UserLoad()
        {
            //if (_users != null) return;
            _users = new Dictionary<string, Individual>();
            Environment.CurrentDirectory = HttpContext.Current.Server.MapPath("/");
            XmlTextReader  xmlFile = new XmlTextReader (_filePath);

             xmlFile.Read();
             while (xmlFile.Read())
             {
                 xmlFile.MoveToElement();
                 if (xmlFile.NodeType == XmlNodeType.Element && xmlFile.Name.Equals("user")){
                     Individual user = new Individual();
                     user.IndividualId = Int16.Parse(xmlFile.GetAttribute("IndividualId"));
                     user.FullName = xmlFile.GetAttribute("FullName").Trim();
                     user.UserName = xmlFile.GetAttribute("UserName").Trim();
                     user.Password = xmlFile.GetAttribute("Password").Trim();
                     user.Email = xmlFile.GetAttribute("Email").Trim();
                     user.PhotoName = xmlFile.GetAttribute("PhotoName").Trim();
                     user.SecurityAnswer = xmlFile.GetAttribute("SecurityAnswer").Trim();
                     user.SecurityQuestion = xmlFile.GetAttribute("SecurityQuestion").Trim();

                     foreach (string s in xmlFile.GetAttribute("Roles").Split(','))
                     {
                         user.addRole(s.Trim());
                     }
                     _users.Add(user.UserName, user);
                 }

             }
             xmlFile.Close();
        }
Ejemplo n.º 2
0
        // logs the user in and accesses their userId and userName
        public static void loginUser(out string userId, out string userName)
        {
            OAuth oAuth = new OAuth();
            oAuth.getOAuthToken();
            string userXML = oAuth.getOAuthDataUrl("http://www.goodreads.com/api/auth_user");
            userId = "";
            userName = "";

            // grab the user name and user id
            XmlTextReader textReader = new XmlTextReader(userXML);

            while (textReader.Read()) {
                textReader.MoveToElement();

                if (textReader.LocalName.Equals("user")) {
                    textReader.MoveToAttribute("id");
                    userId = textReader.Value;
                }

                if (textReader.LocalName.Equals("name")) {
                    userName = textReader.ReadElementContentAsString();
                }

            }
        }
Ejemplo n.º 3
0
        public static void read(string strXMLPath)
        {
            XmlTextReader textReader = new XmlTextReader(strXMLPath);

            textReader.Read();

            // If the node has value

            while (textReader.Read())
            {

                textReader.MoveToElement(); // Move to 1st element
                if (textReader.NodeType.ToString() != "Whitespace" && textReader.NodeType.ToString() != "Element" && textReader.NodeType.ToString() != "EndElement")
                {
                    Console.WriteLine("════════════════════════════════");

             //   Console.WriteLine("Name:" + textReader.Name);
             //   Console.WriteLine("Base URI:" + textReader.BaseURI);
             //   Console.WriteLine("Local Name:" + textReader.LocalName);
             //   Console.WriteLine("Attribute Count:" + textReader.AttributeCount.ToString());
             //   Console.WriteLine("Depth:" + textReader.Depth.ToString());
             //   Console.WriteLine("Line Number:" + textReader.LineNumber.ToString());
             //   Console.WriteLine("Node Type:" + textReader.NodeType.ToString());

                    Console.WriteLine(textReader.Value.ToString());
             }

            }
            Console.Read();
        }
Ejemplo n.º 4
0
        //The Geocoding here i.e getting the latt/long of address
        public void GeoCode()
        {
            //to Read the Stream
            StreamReader sr = null;

            //The Google Maps API Either return JSON or XML. We are using XML Here
            //Saving the url of the Google API
            string url = String.Format("http://maps.googleapis.com/maps/api/geocode/xml?address=" +
            this.Add + "&sensor=false");

            //to Send the request to Web Client
            WebClient wc = new WebClient();
            try
            {
                sr = new StreamReader(wc.OpenRead(url));
            }
            catch (Exception ex)
            {
                throw new Exception("The Error Occured" + ex.Message);
            }

            try
            {
                XmlTextReader xmlReader = new XmlTextReader(sr);
                bool latread = false;
                bool longread = false;

                while (xmlReader.Read())
                {
                    xmlReader.MoveToElement();
                    switch (xmlReader.Name)
                    {
                        case "lat":

                            if (!latread)
                            {
                                xmlReader.Read();
                                this.Latitude = xmlReader.Value.ToString();
                                latread = true;

                            }
                            break;
                        case "lng":
                            if (!longread)
                            {
                                xmlReader.Read();
                                this.Longitude = xmlReader.Value.ToString();
                                longread = true;
                            }

                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("An Error Occured" + ex.Message);
            }
        }
Ejemplo n.º 5
0
        public void GeoCode()
        {
            StreamReader sr = null;

            string url = String.Format("http://maps.googleapis.com/maps/api/geocode/xml?address=" +
            this.Add + "&sensor=true");

            WebClient wc = new WebClient();
            try
            {
                sr = new StreamReader(wc.OpenRead(url));
            }
            catch (Exception ex)
            {
                throw new Exception("The Error Occured" + ex.Message);
            }

            try
            {
                XmlTextReader xmlReader = new XmlTextReader(sr);
                bool latread = false;
                bool longread = false;

                while (xmlReader.Read())
                {
                    xmlReader.MoveToElement();
                    switch (xmlReader.Name)
                    {
                        case "lat":

                            if (!latread)
                            {
                                xmlReader.Read();
                                this.Latitude = xmlReader.Value.ToString();
                                latread = true;

                            }
                            break;
                        case "lng":
                            if (!longread)
                            {
                                xmlReader.Read();
                                this.Longitude = xmlReader.Value.ToString();
                                longread = true;
                            }

                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("An Error Occured" + ex.Message);
            }
        }
Ejemplo n.º 6
0
 public void ExtractElementsFromXML(string element, string inputFile, string outputFile)
 {
     XmlTextReader xmlReader = new XmlTextReader(inputFile);
     StringBuilder sb = new StringBuilder();
     while (xmlReader.Read())
     {
         xmlReader.MoveToElement();
         if (xmlReader.Name.Equals(element))
         {
             sb.Append(xmlReader.ReadElementContentAsString() + "\r\n\r\n");
         }
     }
     TextWriter tw = new StreamWriter(outputFile);
     tw.WriteLine(sb.ToString());
     tw.Close();
 }
Ejemplo n.º 7
0
        public void InterpretXML()
        {
            tickets.Clear();

            XmlTextReader reader;

            try
            {
                reader = new XmlTextReader(serviceURL);

                while (reader.Read() && (reader.NodeType != XmlNodeType.Element || reader.Name != "item")) ;

                while (!reader.EOF)
                {
                    bool enabled = false;
                    String info = "";

                    while (reader.MoveToNextAttribute())
                    {
                        if (reader.Name == "enabled" && reader.Value == "1")
                            enabled = true;
                        else if (reader.Name == "info")
                            info = reader.Value;
                    }

                    reader.MoveToElement();

                    Ticket newTicket = readChilds(reader);
                    newTicket.Enabled = enabled;
                    newTicket.Info = info;
                    tickets.Add(newTicket);

                    while (reader.Read() && (reader.NodeType != XmlNodeType.Element || reader.Name != "item")) ;
                }

                reader.Close();
                reader = null;

                lastUpdate = DateTime.Now;
            }
            catch (Exception)
            {
                tickets.Clear();
                return;
            }
        }
Ejemplo n.º 8
0
 static void Main(string[] args)
 {
     XmlTextReader reader = new XmlTextReader ("Stats.xml");
                 reader.Read();
             while (reader.Read())
             {
               if (reader.HasAttributes)
               {
                         reader.MoveToAttribute("id");
                         string id = reader.Value;
                         reader.MoveToAttribute("Name");
                         string name = reader.Value;
                         Console.WriteLine("| " + id + " | " + name + " |");
                 reader.MoveToElement();
               }
             }
 }
Ejemplo n.º 9
0
 private void Form3_Load(object sender, EventArgs e)
 {
     if (Yasfib.MainForm.isChinese)
     {
         this.Text = "系统日志";
     }
         XmlTextReader textReader = new XmlTextReader("loggy.xml");
         textReader.Read();
         while (textReader.Read())
         {
             textReader.MoveToElement();
             if (textReader.Name == "url")
             {
                 listBox1.Items.Add(textReader.ReadString());
             }
         }
 }
Ejemplo n.º 10
0
        public static void ReadXmlExpenses(string pathToFile)
        {
            XmlTextReader reader = new XmlTextReader(pathToFile);

            string vendorName = string.Empty;
            DateTime date = new DateTime();
            decimal expenses = 0;

            using (reader)
            {
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        if (reader.HasAttributes)
                        {
                            reader.MoveToNextAttribute();
                            if (reader.Name == "vendor")
                            {
                                vendorName = reader.Value;
                            }
                            else if (reader.Name == "month")
                            {
                                date = DateTime.Parse(reader.Value);
                            }
                        }

                        reader.MoveToElement();
                    }

                    if (reader.NodeType == XmlNodeType.Element && reader.Name == "expenses")
                    {
                        var expenseStr = reader.ReadInnerXml();
                        expenses = decimal.Parse(expenseStr);

                        int vendorId = MsSqlManager.InsertExpenses(vendorName, date, expenses);

                        MongoExpense mongoExpense = new MongoExpense(vendorId, date, expenses);

                        MongoDbManager.IsertExpenses(mongoExpense, "mongodb://localhost",
                            "SupermarketProductReports", "Expenses");
                    }
                }
            }
        }
Ejemplo n.º 11
0
    public void Load()
    {
      string e = null;
      XmlTextReader txtReader = new XmlTextReader(_cfgfile);

      while (txtReader.Read())
      {
        txtReader.MoveToElement();
        switch (txtReader.NodeType)
        {
          case XmlNodeType.Element:
            e = txtReader.Name;
            break;
          case XmlNodeType.Text:
            Instance.Set(e, txtReader.Value);
            break;
        }
      }
    }
Ejemplo n.º 12
0
		public override void ReadGen(APGen gen, string streamName, XmlTextReader reader)
		{
			StreamName = streamName;
			GenHost = gen.GenHost;

			while (reader.MoveToNextAttribute())
			{
				switch (reader.Name)
				{
					case "type": TypeName = reader.Value; break;
					case "name": Name = reader.Value; break;
					default: ThrowException(APResource.GetString(APResource.APGen_UnrecognizedAttribute, reader.Name), reader); break;
				}
			}

			if (Name == null || TypeName == null)
				ThrowException(APResource.GetString(APResource.APGen_MissingRequiredAttribute, "section", "name or type"), reader);

			reader.MoveToElement();
			reader.Skip();
		}
Ejemplo n.º 13
0
 static OrderWizard()
 {
     string conditionsDataPath =
         HttpContext.Current.Server.MapPath(PathToJoesPubSeatingConditions);
     XmlTextReader reader = new XmlTextReader(conditionsDataPath);
     if (!reader.ReadToFollowing("pubSeatingConditions"))
         throw new XmlException("Can't find <pubSeatingConditions> node.");
     if (!reader.ReadToDescendant("section"))
         throw new XmlException("Can't find any <section> nodes.");
     syosSeatingConditions = new Dictionary<int, string>();
     do
     {
         if (!reader.MoveToAttribute("id"))
             throw new XmlException("Can't find \"id\" attribute for <section>.");
         int id = Int32.Parse(reader.Value.Trim());
         reader.MoveToElement();
         string conditions = reader.ReadElementContentAsString();
         syosSeatingConditions.Add(id, conditions);
     }
     while (reader.ReadToNextSibling("section"));
 }
        /// <summary>
        /// get theme manifest from xml file
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static JsonPackage GetThemeManifest(string id)
        {
            var jp = new JsonPackage { Id = id };
            var themeUrl = string.Format("{0}themes/{1}/theme.xml", Utils.ApplicationRelativeWebRoot, id);
            var themePath = HttpContext.Current.Server.MapPath(themeUrl);
            try
            {
                if(File.Exists(themePath))
                {
                    var textReader = new XmlTextReader(themePath);
                    textReader.Read();

                    while (textReader.Read())
                    {
                        textReader.MoveToElement();

                        if (textReader.Name == "description")
                            jp.Description = textReader.ReadString();

                        if (textReader.Name == "authors")
                            jp.Authors = textReader.ReadString();

                        if (textReader.Name == "website")
                            jp.Website = textReader.ReadString();

                        if (textReader.Name == "version")
                            jp.Version = textReader.ReadString();

                        if (textReader.Name == "iconurl")
                            jp.IconUrl = textReader.ReadString();
                    }
                    return jp;
                }
            }
            catch (Exception ex)
            {
                Utils.Log("Packaging.FileSystem.GetThemeManifest", ex);
            }
            return null;
        }
Ejemplo n.º 15
0
 public void load(TextReader input)
 {
     XmlTextReader reader = new XmlTextReader(input);
     while (reader.Read())
     {
         if (reader.NodeType == XmlNodeType.Element && reader.Name == "material")
         {
             string matName = "";
             while (reader.MoveToNextAttribute())
             {
                 Utils.print(reader.Name);
                 if (reader.Name == "name")
                 {
                     matName = reader.Value;
                 }
             }
             reader.MoveToElement();
             string matDefinitoion = reader.ReadInnerXml();
             this.create(matName, matDefinitoion);
         }
     }
 }
Ejemplo n.º 16
0
        public static MailModel Load()
        {
            Environment.CurrentDirectory = HttpContext.Current.Server.MapPath("/");
            XmlTextReader xmlFile = new XmlTextReader(_filePath);
            xmlFile.Read();
            MailModel mail = new MailModel();
            while (xmlFile.Read())
            {
                xmlFile.MoveToElement();
                if (xmlFile.NodeType == XmlNodeType.Element && xmlFile.Name.Equals("mail"))
                {
                    mail.SmtpPassWord = xmlFile.GetAttribute("smtpPassword").Trim();
                    mail.SmtpPort = Int16.Parse(xmlFile.GetAttribute("smtpPort"));
                    mail.SmtpServer = xmlFile.GetAttribute("smtpServer").Trim();
                    mail.SmtpUserName = xmlFile.GetAttribute("smtpUserName").Trim();
                    mail.smtpFromEmail = xmlFile.GetAttribute("smtpFromEmail").Trim();
                }

            }
            xmlFile.Close();
            return mail;
        }
Ejemplo n.º 17
0
            public static void ValidateAttributes(XmlTextReader reader, string[] validAttributes)
            {
                if (!reader.HasAttributes)
                    return;

                var list = new List<string>(validAttributes);
                for (int i = 0; i < reader.AttributeCount; i++)
                {
                    reader.MoveToAttribute(i);
                    if (((reader.LocalName != "xmlns") && IsInNamespace(reader)) && !list.Contains(reader.LocalName))
                    {
                        throw Error.SchemaUnrecognizedAttribute(
                            string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}",
                                          new object[]
                                              {
                                                  reader.Prefix, string.IsNullOrEmpty(reader.Prefix) ? "" : ":",
                                                  reader.LocalName
                                              }), reader.LineNumber);
                    }
                }
                reader.MoveToElement();
            }
Ejemplo n.º 18
0
        public void ParsePlaylist(string content)
        {
            this.songs.Clear ();
            this.nextSong = 0;

            XmlTextReader reader = new XmlTextReader (content, XmlNodeType.Element,
                                                      null);

            while (reader.Read ()) {
                reader.MoveToElement ();

                switch (reader.LocalName) {
                case "playlist":
                    int version = Convert.ToInt32 (reader.GetAttribute ("version"));
                    if (version > PLAYLIST_VERSION) {
                        Console.WriteLine ("WARNING: Remote playlist version is: {0} - local version is {1}",
                                           version, PLAYLIST_VERSION);
                    }
                    break;

                case "title":
                    string title = reader.ReadString ();
                    station = HttpUtility.UrlDecode (title);
                    break;

                case "creator":
                    break;

                case "link":
                    break;

                case "track":
                    string xml = reader.ReadInnerXml ();
                    this.songs.Add (ParseSong (xml, station));
                    break;
                }
            }
        }
Ejemplo n.º 19
0
        public static DCompilerConfiguration LoadFromString(string xmlCode)
        {
            var cmp = new DCompilerConfiguration();

            var x = new XmlTextReader(new StringReader(xmlCode));

            if (x.ReadToFollowing("Compiler"))
            {
                if (x.MoveToAttribute("Name"))
                {
                    cmp.Vendor = x.ReadContentAsString();
                    x.MoveToElement();
                }

                cmp.ReadFrom(x);
            }

            x.Close();

            FitFileExtensions(cmp);

            return cmp;
        }
Ejemplo n.º 20
0
		public void RefreshNews()
		{
			new Thread(delegate()
			{
				Thread.CurrentThread.IsBackground = true;
				try
				{
					var data = new System.Net.WebClient().DownloadString("http://d-ide.sourceforge.net/classes/news.php?xml=1&max=20&fromIDE=1");

					var xr = new XmlTextReader(new StringReader(data));
					_LastRetrievedNews.Clear();

					while (xr.Read())
					{
						if (xr.LocalName != "n")
							continue;

						var i = new NewsItem();
						if (xr.MoveToAttribute("id"))
							i.Id = Convert.ToInt32(xr.GetAttribute("id"));
						if (xr.MoveToAttribute("timestamp"))
							i.Timestamp = Util.DateFromUnixTime(Convert.ToInt64(xr.GetAttribute("timestamp")));
						xr.MoveToElement();
						i.Content = Util.StripXmlTags(xr.ReadString());

						_LastRetrievedNews.Add(i);
					}
					xr.Close();
				}
				catch {  }

				NewsList.Dispatcher.Invoke(new Action(delegate()
				{
					NewsList.ItemsSource = _LastRetrievedNews;
				}));
			}).Start();
		}
Ejemplo n.º 21
0
        private void xmlcamera(bool write, string filename = "cameras.xml")
        {
            bool exists = File.Exists(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + filename);

            if (write || !exists)
            {
                try
                {
                    XmlTextWriter xmlwriter = new XmlTextWriter(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + filename, Encoding.ASCII);
                    xmlwriter.Formatting = Formatting.Indented;

                    xmlwriter.WriteStartDocument();

                    xmlwriter.WriteStartElement("Cameras");

                    foreach (string key in cameras.Keys)
                    {
                        try
                        {
                            if (key == "")
                                continue;
                            xmlwriter.WriteStartElement("Camera");
                            xmlwriter.WriteElementString("name", cameras[key].name);
                            xmlwriter.WriteElementString("flen", cameras[key].focallen.ToString(new System.Globalization.CultureInfo("en-US")));
                            xmlwriter.WriteElementString("imgh", cameras[key].imageheight.ToString(new System.Globalization.CultureInfo("en-US")));
                            xmlwriter.WriteElementString("imgw", cameras[key].imagewidth.ToString(new System.Globalization.CultureInfo("en-US")));
                            xmlwriter.WriteElementString("senh", cameras[key].sensorheight.ToString(new System.Globalization.CultureInfo("en-US")));
                            xmlwriter.WriteElementString("senw", cameras[key].sensorwidth.ToString(new System.Globalization.CultureInfo("en-US")));
                            xmlwriter.WriteEndElement();
                        }
                        catch { }
                    }

                    xmlwriter.WriteEndElement();

                    xmlwriter.WriteEndDocument();
                    xmlwriter.Close();

                }
                catch (Exception ex) { CustomMessageBox.Show(ex.ToString()); }
            }
            else
            {
                try
                {
                    using (XmlTextReader xmlreader = new XmlTextReader(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + filename))
                    {
                        while (xmlreader.Read())
                        {
                            xmlreader.MoveToElement();
                            try
                            {
                                switch (xmlreader.Name)
                                {
                                    case "Camera":
                                        {
                                            camerainfo camera = new camerainfo();

                                            while (xmlreader.Read())
                                            {
                                                bool dobreak = false;
                                                xmlreader.MoveToElement();
                                                switch (xmlreader.Name)
                                                {
                                                    case "name":
                                                        camera.name = xmlreader.ReadString();
                                                        break;
                                                    case "imgw":
                                                        camera.imagewidth = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US"));
                                                        break;
                                                    case "imgh":
                                                        camera.imageheight = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US"));
                                                        break;
                                                    case "senw":
                                                        camera.sensorwidth = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US"));
                                                        break;
                                                    case "senh":
                                                        camera.sensorheight = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US"));
                                                        break;
                                                    case "flen":
                                                        camera.focallen = float.Parse(xmlreader.ReadString(), new System.Globalization.CultureInfo("en-US"));
                                                        break;
                                                    case "Camera":
                                                        cameras[camera.name] = camera;
                                                        dobreak = true;
                                                        break;
                                                }
                                                if (dobreak)
                                                    break;
                                            }
                                            string temp = xmlreader.ReadString();
                                        }
                                        break;
                                    case "Config":
                                        break;
                                    case "xml":
                                        break;
                                    default:
                                        if (xmlreader.Name == "") // line feeds
                                            break;
                                        //config[xmlreader.Name] = xmlreader.ReadString();
                                        break;
                                }
                            }
                            catch (Exception ee) { Console.WriteLine(ee.Message); } // silent fail on bad entry
                        }
                    }
                }
                catch (Exception ex) { Console.WriteLine("Bad Camera File: " + ex.ToString()); } // bad config file

                // populate list
                foreach (var camera in cameras.Values)
                {
                    if (!CMB_camera.Items.Contains(camera.name))
                        CMB_camera.Items.Add(camera.name);
                }
            }
        }
        private static void read_engine_file(string ConfigFile, Microservice_Server_Configuration Config, List<Microservice_Endpoint> AllEndpoints, Dictionary<Microservice_VerbMapping, string> EndpointToComponentDictionary, Dictionary<Microservice_VerbMapping, string> EndpointToRestrictionDictionary, Dictionary<string, Microservice_Component> Components, Dictionary<string, Microservice_RestrictionRange> Ranges)
        {
            // Streams used for reading
            Stream readerStream = null;
            XmlTextReader readerXml = null;

            try
            {
                // Open a link to the file
                readerStream = new FileStream(ConfigFile, FileMode.Open, FileAccess.Read);

                // Open a XML reader connected to the file
                readerXml = new XmlTextReader(readerStream);

                while (readerXml.Read())
                {
                    if (readerXml.NodeType == XmlNodeType.Element)
                    {
                        switch (readerXml.Name.ToLower())
                        {
                            case "engine":
                                if (readerXml.MoveToAttribute("ClearAll"))
                                {
                                    if (readerXml.Value.Trim().ToLower() == "true")
                                    {
                                        Config.ClearAll();
                                        AllEndpoints.Clear();
                                        Components.Clear();
                                        Ranges.Clear();
                                        EndpointToComponentDictionary.Clear();
                                        EndpointToRestrictionDictionary.Clear();
                                    }
                                    readerXml.MoveToElement();
                                }
                                read_engine_details(readerXml.ReadSubtree(), Config, AllEndpoints, EndpointToComponentDictionary, EndpointToRestrictionDictionary, Components, Ranges);
                                break;
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                Config.Error = ee.Message;
            }
            finally
            {
                if (readerXml != null)
                {
                    readerXml.Close();
                }
                if (readerStream != null)
                {
                    readerStream.Close();
                }
            }
        }
Ejemplo n.º 23
0
        private void xmlconfig(bool write)
        {
            if (write || !File.Exists(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"config.xml"))
            {
                try
                {
                    log.Info("Saving config");

                    XmlTextWriter xmlwriter = new XmlTextWriter(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"config.xml", Encoding.UTF8);
                    xmlwriter.Formatting = Formatting.Indented;

                    xmlwriter.WriteStartDocument();

                    xmlwriter.WriteStartElement("Config");

                    xmlwriter.WriteElementString("comport", comPortName);

                    xmlwriter.WriteElementString("baudrate", _connectionControl.CMB_baudrate.Text);

                    xmlwriter.WriteElementString("APMFirmware", MainV2.comPort.MAV.cs.firmware.ToString());

                    foreach (string key in config.Keys)
                    {
                        try
                        {
                            if (key == "" || key.Contains("/")) // "/dev/blah"
                                continue;
                            xmlwriter.WriteElementString(key, config[key].ToString());
                        }
                        catch { }
                    }

                    xmlwriter.WriteEndElement();

                    xmlwriter.WriteEndDocument();
                    xmlwriter.Close();
                }
                catch (Exception ex) { CustomMessageBox.Show(ex.ToString()); }
            }
            else
            {
                try
                {
                    using (XmlTextReader xmlreader = new XmlTextReader(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"config.xml"))
                    {
                        log.Info("Loading config");

                        while (xmlreader.Read())
                        {
                            xmlreader.MoveToElement();
                            try
                            {
                                switch (xmlreader.Name)
                                {
                                    case "comport":
                                        string temp = xmlreader.ReadString();

                                        _connectionControl.CMB_serialport.SelectedIndex = _connectionControl.CMB_serialport.FindString(temp);
                                        if (_connectionControl.CMB_serialport.SelectedIndex == -1)
                                        {
                                            _connectionControl.CMB_serialport.Text = temp; // allows ports that dont exist - yet
                                        }
                                        comPort.BaseStream.PortName = temp;
                                        comPortName = temp;
                                        break;
                                    case "baudrate":
                                        string temp2 = xmlreader.ReadString();

                                        _connectionControl.CMB_baudrate.SelectedIndex = _connectionControl.CMB_baudrate.FindString(temp2);
                                        if (_connectionControl.CMB_baudrate.SelectedIndex == -1)
                                        {
                                            _connectionControl.CMB_baudrate.Text = temp2;
                                            //CMB_baudrate.SelectedIndex = CMB_baudrate.FindString("57600"); ; // must exist
                                        }
                                        //bau = int.Parse(CMB_baudrate.Text);
                                        break;
                                    case "APMFirmware":
                                        string temp3 = xmlreader.ReadString();
                                        _connectionControl.TOOL_APMFirmware.SelectedIndex = _connectionControl.TOOL_APMFirmware.FindStringExact(temp3);
                                        if (_connectionControl.TOOL_APMFirmware.SelectedIndex == -1)
                                            _connectionControl.TOOL_APMFirmware.SelectedIndex = 0;
                                        MainV2.comPort.MAV.cs.firmware = (MainV2.Firmwares)Enum.Parse(typeof(MainV2.Firmwares), _connectionControl.TOOL_APMFirmware.Text);
                                        break;
                                    case "Config":
                                        break;
                                    case "xml":
                                        break;
                                    default:
                                        if (xmlreader.Name == "") // line feeds
                                            break;
                                        config[xmlreader.Name] = xmlreader.ReadString();
                                        break;
                                }
                            }
                            // silent fail on bad entry
                            catch (Exception ee)
                            {
                                log.Error(ee);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Error("Bad Config File", ex);
                }
            }
        }
        public void ScanDir(string pathToDir)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(pathToDir);

            foreach (FileInfo langFile in dirInfo.GetFiles("*.lng"))
            {
                using (XmlTextReader xmlRdr = new XmlTextReader(langFile.FullName))
                {
                    xmlRdr.Read();

                    while (xmlRdr.Read())
                    {
                        xmlRdr.MoveToElement();
                        if (xmlRdr.LocalName == "language")
                        {
                            if (_appCode == xmlRdr.GetAttribute("appcode"))
                            {
                                try
                                {
                                    _files.Add(xmlRdr.GetAttribute("code"), langFile.FullName);
                                    _langs.Add(xmlRdr.GetAttribute("code"), xmlRdr.GetAttribute("title"));
                                }
                                catch
                                {
                                }
                            }
                        }
                    }
                }
            }
        }
        internal IList Deserialize(IServiceProvider serviceProvider)
        {
            DesignerSerializationManager serializationManager = new LocalDesignerSerializationManager(this, serviceProvider);
            using (serializationManager.CreateSession())
            {
                ArrayList objects = new ArrayList();
                WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(serializationManager);
                XmlTextReader reader = new XmlTextReader(this.serializedXmlString, XmlNodeType.Element, null);
                reader.MoveToElement();
                do
                {
                    if (!reader.Read())
                        return objects;

                    xomlSerializationManager.FoundDefTag += delegate(object sender, WorkflowMarkupElementEventArgs eventArgs)
                    {
                        if (eventArgs.XmlReader.LookupNamespace(eventArgs.XmlReader.Prefix) == StandardXomlKeys.Definitions_XmlNs &&
                            xomlSerializationManager.Context.Current is Activity
                            )
                            WorkflowMarkupSerializationHelpers.ProcessDefTag(xomlSerializationManager, eventArgs.XmlReader, xomlSerializationManager.Context.Current as Activity, true, string.Empty);
                    };

                    WorkflowMarkupSerializer xomlSerializer = new WorkflowMarkupSerializer();
                    object activityDecl = xomlSerializer.DeserializeObject(xomlSerializationManager, reader);
                    if (activityDecl == null)
                        throw new InvalidOperationException(DR.GetString(DR.InvalidOperationDeserializationReturnedNonActivity));
                    if (activityDecl is Activity)
                        (activityDecl as Activity).UserData.Remove(UserDataKeys.CustomActivity);
                    objects.Add(activityDecl);
                } while (true);
            }
        }
        public void LoadLanguage(string langTitle)
        {
            if (_langs.ContainsValue(langTitle))
            {
                try
                {
                    string languageFilePath;

                    _files.TryGetValue(ValueToKey(langTitle), out languageFilePath);

                    if (languageFilePath.Trim() != string.Empty)
                    {
                        using (XmlTextReader langReader = new XmlTextReader(languageFilePath))
                        {
                            langReader.Read();
                            while (langReader.Read())
                            {
                                langReader.MoveToElement();
                                if (langReader.LocalName == "Label1")
                                {
                                    _label1 = langReader.GetAttribute("caption");
                                }

                                if (langReader.LocalName == "Label2")
                                {
                                    _label2 = langReader.GetAttribute("caption");
                                }

                                if (langReader.LocalName == "Menu1")
                                {
                                    _menu1 = langReader.GetAttribute("caption");
                                }

                                if (langReader.LocalName == "LanguageNotFound")
                                {
                                    _languageNotFound = langReader.GetAttribute("caption");
                                }
                            }
                        }
                    }
                }

                catch
                { }
            }
            else
            {
                throw new LanguageNotFoundException();
            }
        }
Ejemplo n.º 27
0
        protected Vector3 parseVectorAttributes(XmlTextReader r)
        {
            float x = 0;
            float y = 0;
            float z = 0;

            for (int i = 0; i < r.AttributeCount; i++)
            {
                r.MoveToAttribute(i);

                // set the field in this object based on the element we just read
                switch (r.Name)
                {
                    case "WorldViewSelect":
                        worldViewSelectable = bool.Parse(r.Value);
                        break;
                    case "x":
                        x = float.Parse(r.Value);
                        break;
                    case "y":
                        y = float.Parse(r.Value);
                        break;
                    case "z":
                        z = float.Parse(r.Value);
                        break;
                }
            }
            r.MoveToElement(); //Moves the reader back to the element node.

            return new Vector3(x, y, z);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Reads the stock data from a FIXML file, predicts its trends and save it in the memory.
        /// </summary>
        /// <param name="predictorName">Name of the prediction plugin.</param>
        /// <param name="xmlFilePath">Path to the FIXML file.</param>
        private void UpdateStockData(String predictorName, String xmlFilePath)
        {
            XmlTextReader reader = new XmlTextReader(xmlFilePath);
            reader.WhitespaceHandling = WhitespaceHandling.None;

            String stockName = String.Empty;
            String stockPriceString = String.Empty;
            String stockTransactionTime = String.Empty;

            while (reader.Read())
            {
                if (reader.Name.Equals("Order") && reader.NodeType == XmlNodeType.Element)
                {
                    #region XML parsing
                    // Get the attributes we want from <Order>
                    stockTransactionTime = reader.GetAttribute("TransactTm");
                    stockPriceString = reader.GetAttribute("Px");

                    // Move back to <Order> node
                    reader.MoveToElement();

                    // Move to <Hdr> node and skip it's children
                    reader.Read();
                    reader.Skip();

                    // We are in <Instrmt> node. Get the attribute we want
                    stockName = reader.GetAttribute("Sym");
                    reader.MoveToElement();
                    #endregion XML parsing

                    #region Data manipulation
                    // Convert stockPriceString to uint - discard decimals
                    Debug.Assert(stockPriceString != null);
                    uint stockPrice = Convert.ToUInt32(stockPriceString.Split(',')[0]);

                    // Convert stockTransactionTime to long
                    // Format of stockTransactionTime: YYYY-MM-DDTHH:MM:SS
                    Debug.Assert(stockTransactionTime != null);
                    int year = Convert.ToInt32(stockTransactionTime.Substring(0, 4));
                    int month = Convert.ToInt32(stockTransactionTime.Substring(5, 2));
                    int day = Convert.ToInt32(stockTransactionTime.Substring(8, 2));
                    int hour = Convert.ToInt32(stockTransactionTime.Substring(11, 2));
                    int minute = Convert.ToInt32(stockTransactionTime.Substring(14, 2));
                    int second = Convert.ToInt32(stockTransactionTime.Substring(17, 2));

                    // Get milliseconds since unixStartDate
                    //DateTime unixStartDate = new DateTime(1970, 1, 1);
                    DateTime stockTime = new DateTime(year, month, day, hour, minute, second);
                    //long ticksSinceUnixStartDate = stockTime.Ticks - unixStartDate.Ticks;
                    long stockTimeStampMillis = stockTime.Ticks / 10000000; // 10.000.000 ticks = 1 second

                    // Save the data
                    int i = -1;
                    i = stockGroups.FindIndex(stockGroup => stockGroup.Name.Equals(stockName));
                    if (i != -1)
                    {
                        // stockName already exist in stockGroups
                        // Add new values to stockName's data points
                        List<StockDataPoint> dataPoints = stockGroups[i].DataPoints;
                        dataPoints.Add(new StockDataPoint(stockPrice, stockTimeStampMillis));
                        stockGroups[i].DataPoints = dataPoints;
                    }
                    else
                    {
                        // stockName does not exist in stockGroups
                        // Create new list of data points
                        List<StockDataPoint> dataPoints = new List<StockDataPoint>();
                        // Add the initial stock price to the list
                        dataPoints.Add(new StockDataPoint(stockPrice, stockTimeStampMillis));
                        // Add the new stockName to stockGroups
                        stockGroups.Add(new StockGroup(stockName, dataPoints));
                    }
                    #endregion Data manipulation
                }
            }

            foreach (StockGroup stockGroup in stockGroups)
            {
                Log.Write("Stock name: " + stockGroup.Name);
            }

            Log.Write("Searching for " + predictorName + ".dll in plugins folder");
            Assembly predictionAssembly = Assembly.LoadFrom("./plugins/" + predictorName + ".dll");
            StockPrediction predictor = null;

            foreach (Type type in predictionAssembly.GetTypes())
            {
                Log.Write(" > Found: " + type.Name);
                if (type.IsClass && type.GetInterface("StockPrediction") != null)
                {
                    Log.Write("a Stock predictor was found");
                    predictor = Activator.CreateInstance(type, new object[0]) as StockPrediction;
                }
            }

            if (predictor == null)
                Log.Write("No stock predictor was found in the dll file");

            // Call prediction on all stock groups
            foreach (StockGroup stockGroup in stockGroups)
            {
                predictor.Predict(stockGroup);
            }

            Log.Write("Current time in seconds: " + (DateTime.Now - new DateTime()).TotalSeconds);
        }
Ejemplo n.º 29
0
 static void WriteAttributes(TextWriter output, XmlTextReader xtr)
 {
     for (int i = 0; i < xtr.AttributeCount; i++)
     {
         xtr.MoveToAttribute(i);
         if (xtr.Prefix == "xml")
             continue;
         output.Write(" <span class='a'>{0}</span>=<span class='at'>\"{1}\"</span>", xtr.Name, xtr.Value);
     }
     xtr.MoveToElement();
 }
Ejemplo n.º 30
0
        private void xmlconfig(bool write)
        {
            if (write || !File.Exists(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"config.xml"))
            {
                try
                {
                    XmlTextWriter xmlwriter = new XmlTextWriter(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"config.xml", Encoding.ASCII);
                    xmlwriter.Formatting = Formatting.Indented;

                    xmlwriter.WriteStartDocument();

                    xmlwriter.WriteStartElement("Config");

                    xmlwriter.WriteElementString("comport", CMB_ComPort.Text);

                    xmlwriter.WriteElementString("Pal", CHK_pal.Checked.ToString());

                    xmlwriter.WriteEndElement();

                    xmlwriter.WriteEndDocument();
                    xmlwriter.Close();

                    //appconfig.Save();
                }
                catch (Exception ex) { MessageBox.Show(ex.ToString()); }
            }
            else
            {
                try
                {
                    using (XmlTextReader xmlreader = new XmlTextReader(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + @"config.xml"))
                    {
                        while (xmlreader.Read())
                        {
                            xmlreader.MoveToElement();
                            try
                            {
                                switch (xmlreader.Name)
                                {
                                    case "comport":
                                        string temp = xmlreader.ReadString();
                                        CMB_ComPort.Text = temp;
                                        break;
                                    case "Pal":
                                        string temp2 = xmlreader.ReadString();
                                        //CHK_pal.Checked = (temp2 == "True");
                                        break;
                                    case "Config":
                                        break;
                                    case "xml":
                                        break;
                                    default:
                                        if (xmlreader.Name == "") // line feeds
                                            break;
                                        break;
                                }
                            }
                            catch (Exception ee) { Console.WriteLine(ee.Message); } // silent fail on bad entry
                        }
                    }
                }
                catch (Exception ex) { Console.WriteLine("Bad Config File: " + ex.ToString()); } // bad config file
            }
        }
Ejemplo n.º 31
0
 // Move to the element that owns the current attribute.
 public override bool MoveToElement()
 {
     return(reader.MoveToElement());
 }