示例#1
0
文件: test.cs 项目: mono/gert
	static void Main (string [] args)
	{
		string schemaFile = "bug.xsd";
		XmlTextReader treader = new XmlTextReader (schemaFile);

		XmlSchema sc = XmlSchema.Read (treader, null);
		sc.Compile (null);

		string page =
			"<body xmlns=\"" + sc.TargetNamespace + "\">"
			+ "<div>"
			+ "</div>"
			+ "</body>";

		System.Xml.XmlTextReader reader = new XmlTextReader (new StringReader (page));
		try {
			XmlValidatingReader validator = new System.Xml.XmlValidatingReader (reader);
			validator.Schemas.Add (sc);
			validator.ValidationType = ValidationType.Schema;
			validator.EntityHandling = EntityHandling.ExpandCharEntities;
			while (validator.Read ()) {
			}
		} finally {
			reader.Close ();
		}
	}
    private static string ReadXml(string filename, int ID)
    {
        string strLastVersion = "";

        XmlTextReader reader = new XmlTextReader(filename);

        while (reader.Read())
        {
            if (reader.HasAttributes)
            {
                while (reader.MoveToNextAttribute())
                {
                    if (reader.Name == "id")
                    {
                        if (reader.Value == ID.ToString())
                        {
                            strLastVersion = reader.ReadString();
                            reader.Close();
                            return strLastVersion;
                        }
                    }
                }
            }
        }

        return strLastVersion;
    }
    public void SetAppTypeProduct()
    {
        try
        {
            XmlDocument doc = new XmlDocument();
            string xpath = Server.MapPath("../data/xml/configproduct.xml");
            XmlTextReader reader = new XmlTextReader(xpath);
            doc.Load(reader);
            reader.Close();
            XmlNodeList nodes = doc.SelectNodes("/root/product");
            int numnodes = nodes.Count;
            for (int i = 0; i < numnodes; i++)
            {
                string nameapp = nodes.Item(i).ChildNodes[0].InnerText;
                string idtype = nodes.Item(i).ChildNodes[1].InnerText;
                string appunit = nodes.Item(i).ChildNodes[2].InnerText;
                string unit = nodes.Item(i).ChildNodes[3].InnerText;
                if (nameapp.Length > 0 && idtype.Length > 0)
                {
                    Application[nameapp] = int.Parse(idtype);
                }
                if (appunit.Length > 0 && unit.Length > 0)
                {
                    Application[appunit] = unit;
                }
            }
        }
        catch
        {

        }
    }
 protected void Button1_ServerClick(object sender, EventArgs e)
 {
     try
     {
         string currency = idChoice.Value;
         XmlDocument doc = new XmlDocument();
         string url = Server.MapPath("../data/xml/configproduct.xml");
         XmlTextReader reader = new XmlTextReader(url);
         doc.Load(reader);
         reader.Close();
         if (doc.IsReadOnly)
         {
             diverr.Visible = true;
             diverr.InnerHtml = "File XML đã bị khóa. Không thể thay đổi";
             return;
         }
         XmlNode nodeEdit = doc.SelectSingleNode("root/product[nameappunit='currency']/unit");
         string value = nodeEdit.InnerText;
         if (!value.Equals(currency))
         {
             nodeEdit.InnerText = currency;
             doc.Save(url);
             Application["currency"] = currency;
             diverr.Visible = true;
             diverr.InnerHtml = "Đã thay đổi cách hiển thị tiền tệ";
         }
         else
         {
             diverr.Visible = true;
             diverr.InnerHtml = "Hệ thống đang hiển thị kiểu tiền này.";
         }
     }catch
     {}
 }
示例#5
0
	private void ReadXML()
	{
		string xmlFile = Server.MapPath("DvdList.xml");

		// Create the reader.
		XmlTextReader reader = new XmlTextReader(xmlFile);

		StringBuilder str = new StringBuilder();
		reader.ReadStartElement("DvdList");

		// Read all the <DVD> elements.
		while (reader.Read())
		{
			if ((reader.Name == "DVD") && (reader.NodeType == XmlNodeType.Element))
			{
				reader.ReadStartElement("DVD");
				str.Append("<ul><b>");
				str.Append(reader.ReadElementString("Title"));
				str.Append("</b><li>");
				str.Append(reader.ReadElementString("Director"));
				str.Append("</li><li>");
				str.Append(String.Format("{0:C}",
					Decimal.Parse(reader.ReadElementString("Price"))));
				str.Append("</li></ul>");
			}
		}
		// Close the reader and show the text.
		reader.Close();
		XmlText.Text = str.ToString();
	}
示例#6
0
        static void FindInXML(string file, string teg, string val)
        {
            XmlTextReader reader = null;

            try
            {
                reader = new XmlTextReader(file);
                reader.WhitespaceHandling = WhitespaceHandling.None;
                while (reader.Read())
                {
                    if (reader.Name == teg)
                    {
                        if (reader.Read() && reader.Value == val)
                        {
                            Console.WriteLine($"find {reader.Name}\t\t{reader.Value}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                reader?.Close();
            }
        }
    public List<string> GetDialogById(string id)
    {
        XmlTextReader reader = new XmlTextReader(XMLFileName);
        List<string> texts   = new List<string>();

        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element && reader.Name == id)
            {
                int i = 0;
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.EndElement && reader.Name == id)
                    {
                        break;
                    }
                    if (reader.NodeType == XmlNodeType.Element && reader.Name == ("text_" + i))
                    {
                        texts.Add(reader.ReadElementContentAsString());
                        i++;
                    }
                }
            }
        }
        reader.Close();

        return texts;
    }
示例#8
0
	public static string GetTargetNamespace (string src)
	{
		XmlTextReader reader = null;
		try
		{
			reader = new XmlTextReader (src);
			reader.WhitespaceHandling = WhitespaceHandling.None;
			while (reader.Read())
			{
				if (reader.NodeType == XmlNodeType.Element &&
				reader.LocalName == "schema")
				{
					while (reader.MoveToNextAttribute ())
					{
						if (reader.Name == "targetNamespace")
							return reader.Value;
					}
				}
			}
			return "";
		}	
		finally 
		{
			if (reader != null)
				reader.Close ();
		}
	}
示例#9
0
        public static T ConvertToObject <T>(string xml, out string messages)
        {
            messages = string.Empty;

            StringReader  stream = null;
            XmlTextReader reader = null;

            try
            {
                // serialise to object
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                stream = new StringReader(xml);     // read xml data
                reader = new XmlTextReader(stream); // create reader
                // covert reader to object
                return((T)serializer.Deserialize(reader));
            }
            catch (Exception ex)
            {
                messages = ex.Message;
                if (ex.InnerException != null)
                {
                    messages += " [ " + ex.InnerException.Message + " ]";
                }
                return(default(T));
            }
            finally
            {
                stream?.Close();
                reader?.Close();
            }
        }
示例#10
0
  static void Main(string[] args)
  {
    string localURL = @"http://ip-address.domaintools.com/myip.xml";
    XmlTextReader xmlreader = null;
    xmlreader = new XmlTextReader (localURL);

    while (xmlreader.Read())
    {
    
    	if(xmlreader.NodeType == XmlNodeType.Element)
    	{
    	
    			Console.WriteLine("Element : " + xmlreader.Name);
    
    	} 

    	if(xmlreader.NodeType == XmlNodeType.Text)
    	{
    		Console.WriteLine("Value : " +xmlreader.Value);
    	}
    }
    if (xmlreader != null)
      xmlreader.Close();

  }
        ////////////////////////////////////////////////////////////////////
        // Load Program State
        ////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Load Program State
        /// </summary>
        /// <param name="fileName">Refresh token file name</param>
        /// <returns>Refresh token class</returns>
        public static SecureSmtpRefreshToken LoadState(string fileName)
        {
            // program state file does not exist
            if (!File.Exists(fileName))
            {
                return(null);
            }

            XmlTextReader          textFile = null;
            SecureSmtpRefreshToken state    = null;

            try
            {
                // read program state file
                textFile = new XmlTextReader(fileName);

                // create xml serializing object
                var xmlFile = new XmlSerializer(typeof(SecureSmtpRefreshToken));

                // deserialize the program state
                state = (SecureSmtpRefreshToken)xmlFile.Deserialize(textFile);
            }
            catch
            {
                state = null;
            }

            // close the file
            textFile?.Close();

            // exit
            return(state);
        }
示例#12
0
    public static List<string> ReadXml(string path, string colum)
    {
        List<string> listOfElements = new List<string>();

        XmlTextReader textReader = new XmlTextReader(path);

        int foundName = 0;

        while (textReader.Read())
        {
            if (foundName > 0 && textReader.Name != string.Empty && !String.Equals(textReader.Name, colum, StringComparison.CurrentCultureIgnoreCase))
                foundName = 0;

            if (foundName == 2 && String.Equals(textReader.Name, colum, StringComparison.CurrentCultureIgnoreCase))
            {
                foundName = 0; continue;
            }

            if (foundName == 0 && String.Equals(textReader.Name, colum, StringComparison.CurrentCultureIgnoreCase))
            {
                foundName = 1; continue;
            }

            if (foundName != 1 || textReader.Name != string.Empty) continue;

            listOfElements.Add(textReader.Value);
        }

        textReader.Close();
        return listOfElements;
    }
	static void RunTest ()
	{
		foreach (DirectoryInfo di in new DirectoryInfo (@"relax-ng").GetDirectories ()) {
			XmlTextReader xtr = null;
			FileInfo fi = new FileInfo (di.FullName + "/i.rng");
			// Invalid grammar case:
			if (fi.Exists) {
				xtr = new XmlTextReader (fi.FullName);
				try {
					RelaxngPattern.Read (xtr).Compile ();
					Console.WriteLine ("Expected error: " + di.Name);
				} catch (RelaxngException ex) {
				} catch (XmlException ex) {
				} catch (ArgumentNullException ex) {
				} catch (UriFormatException ex) {
				} catch (Exception ex) {
					Console.WriteLine ("Unexpected error type : " + di.Name + " : " + ex.Message);
				} finally {
					xtr.Close ();
				}
				continue;
			}

			// Valid grammar case:
			xtr = new XmlTextReader (di.FullName + "/c.rng");
			RelaxngPattern p = null;
			try {
				p = RelaxngPattern.Read (xtr);
				p.Compile ();
				} catch (Exception ex) {
					Console.WriteLine ("Invalidated grammar: " + di.Name + " : " + ex.Message);
					continue;
			} finally {
				xtr.Close ();
			}


			// Instance validation
			foreach (FileInfo inst in di.GetFiles ("*.xml")) {
				try {
					RelaxngValidatingReader vr = new RelaxngValidatingReader (new XmlTextReader (inst.FullName), p);
					if (skip_error)
						vr.InvalidNodeFound += RelaxngValidatingReader.IgnoreError;
					while (!vr.EOF)
						vr.Read ();
					if (inst.Name.IndexOf ("i.") >= 0 && !skip_error)
						Console.WriteLine ("Incorrectly validated instance: " + di.Name + "/" + inst.Name);
				} catch (RelaxngException ex) {
					string path = di.Name + "/" + inst.Name;
					if (skip_error)
						Console.WriteLine ("Failed to skip error : " + path + ex.Message);
					if (inst.Name.IndexOf ("i.") >= 0)
						continue;
					Console.WriteLine ("Invalidated instance: " + path + " : " + ex.Message);
				}
			}
		}
	}
示例#14
0
    public static CBWProcessor Load(string filename)
    {
        XmlTextReader reader = new XmlTextReader (filename);
        XmlDocument doc = new XmlDocument ();

        doc.Load (reader);
        reader.Close ();

        XmlNode root = doc.DocumentElement;

        if (root.Name != "bw")
            throw new ApplicationException ("Wrong root node");

        XmlNode node = root.FirstChild;
        if (node.Name != "load")
            throw new ApplicationException ("Could not find load node");
        CBWProcessor processor = new CBWProcessor (node.InnerText);

        node = node.NextSibling;
        if (node.Name != "mixer")
            throw new ApplicationException ("Could not find mixer node");

        processor.Red = (float)Double.Parse (node.Attributes.GetNamedItem ("red").Value);
        processor.Green = (float)Double.Parse (node.Attributes.GetNamedItem ("green").Value);
        processor.Blue = (float)Double.Parse (node.Attributes.GetNamedItem ("blue").Value);

        node = node.NextSibling;
        if (node.Name != "contrast")
            throw new ApplicationException ("Could not find contrast node");

        Curve curve = processor.ContrastCurve;
        while (curve.NumPoints () > 0)
            curve.RemovePointIndex (0);

        XmlNode curveNode = node.FirstChild;
        if (curveNode.Name != "curve")
            throw new ApplicationException ("Could not find curve node");
        curveNode = curveNode.FirstChild;
        while (curveNode != null) {
            if (curveNode.Name != "point")
                throw new ApplicationException ("Could not find point node");

            curve.AddPoint ((float)Double.Parse (curveNode.Attributes.GetNamedItem ("x").Value),
                            (float)Double.Parse (curveNode.Attributes.GetNamedItem ("y").Value));

            curveNode = curveNode.NextSibling;
        }

        node = node.NextSibling;
        if (node.Name != "tint")
            throw new ApplicationException ("Could not find tint node");

        processor.TintHue = (float)Double.Parse (node.Attributes.GetNamedItem ("hue").Value);
        processor.TintAmount = (float)Double.Parse (node.Attributes.GetNamedItem ("amount").Value);

        return processor;
    }
示例#15
0
        public override FileMetadata AnalyzeFile()
        {
            XmlTextReader avgReader = null;

            try
            {
                this.foundMetadata = new FileMetadata();
                avgReader          = new XmlTextReader(this.fileStream)
                {
                    XmlResolver = null
                };
                avgReader.Read();

                while (avgReader.Read())
                {
                    // node's value, example: <a>/home/user/file</a>
                    if (CheckPath(avgReader.Value))
                    {
                        var cleanPath = PathAnalysis.CleanPath(avgReader.Value);
                        var user      = PathAnalysis.ExtractUserFromPath(cleanPath);
                        if (user != string.Empty)
                        {
                            this.foundMetadata.Add(new User(user, true));
                        }
                        this.foundMetadata.Add(new Diagrams.Path(cleanPath, true));
                    }

                    while (avgReader.MoveToNextAttribute())
                    {
                        // attribute's value, example: <a atrib="/home/user/file"/>
                        if (!CheckPath(avgReader.Value))
                        {
                            continue;
                        }
                        var cleanPath = PathAnalysis.CleanPath(avgReader.Value);
                        var user      = PathAnalysis.ExtractUserFromPath(cleanPath);
                        if (user != string.Empty)
                        {
                            this.foundMetadata.Add(new User(user, true));
                        }
                        this.foundMetadata.Add(new Diagrams.Path(cleanPath, true));
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("error: " + ex.Message);
            }
            finally
            {
                avgReader?.Close();
            }
            return(this.foundMetadata);
        }
示例#16
0
    public static Levels DeserializeStringToObject(TextAsset xmlTextAsset)
    {
        MemoryStream memStream = new MemoryStream (xmlTextAsset.bytes);
        XmlTextReader xmlReader = new XmlTextReader (memStream);
        var serializer = new XmlSerializer (typeof(Levels));
        Levels lvl = serializer.Deserialize (xmlReader) as Levels;

        xmlReader.Close ();
        memStream.Close ();

        return lvl;
    }
示例#17
0
    public bool LoadItems()
    {
        Item item = null;

        if(File.Exists(file))
        {
            XmlTextReader reader = new XmlTextReader(file);
            while(reader.Read())
            {
                switch(reader.Name.ToString().ToLower())
                {
                    case "item": //assuming there is more than one item
                        item = new Item();
                        if(reader.HasAttributes)
                        {
                            while(reader.MoveToNextAttribute())
                            {
                                switch(reader.Name.ToString().ToLower())
                                {
                                    case "id":
                                        item.id = Convert.ToInt32(reader.Value);
                                        break;
                                    case "name":
                                        item.name = reader.Value;
                                        break;
                                    case "description":
                                        item.description = reader.Value;
                                        break;
                                    case "file":
                                        item.fileDir = reader.Value;
                                        break;
                                    case "base": //base position declared
                                        string val = reader.Value;
                                        string[] split = val.Split(',');
                                        item.basePosition = new Vector3(float.Parse(split[0]), float.Parse(split[1]), float.Parse(split[2]));
                                        break;
                                }
                            }
                            //if we get this point, it's mean there is no more attrs to read
                            if (item != null)
                            {
                                items.Add(item);
                            }
                        }
                        break;
                }
            }
            reader.Close();
            loaded = true;
        }
        return loaded;
    }
示例#18
0
        public override void analyzeFile()
        {
            XmlTextReader avgReader = null;

            try
            {
                avgReader = new XmlTextReader(this.stm)
                {
                    XmlResolver = null
                };
                avgReader.Read();

                while (avgReader.Read())
                {
                    // node's value, example: <a>/home/user/file</a>
                    if (CheckPath(avgReader.Value))
                    {
                        var cleanPath = PathAnalysis.CleanPath(avgReader.Value);
                        var user      = PathAnalysis.ExtractUserFromPath(cleanPath);
                        if (user != string.Empty)
                        {
                            FoundUsers.AddUniqueItem(user, true);
                        }
                        FoundPaths.AddUniqueItem(cleanPath, true);
                    }

                    while (avgReader.MoveToNextAttribute())
                    {
                        // attribute's value, example: <a atrib="/home/user/file"/>
                        if (!CheckPath(avgReader.Value))
                        {
                            continue;
                        }
                        var cleanPath = PathAnalysis.CleanPath(avgReader.Value);
                        var user      = PathAnalysis.ExtractUserFromPath(cleanPath);
                        if (user != string.Empty)
                        {
                            FoundUsers.AddUniqueItem(user, true);
                        }
                        FoundPaths.AddUniqueItem(cleanPath, true);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("error: " + ex.Message);
            }
            finally
            {
                avgReader?.Close();
            }
        }
    /// <summary>
    /// Create an instance of an object from file.
    /// </summary>
    /// <param name="path">Path to the XML file</param>
    /// <param name="type">Type of object to create</param>
    /// <returns></returns>
    public static object Load( string path, Type type )
    {
        object thing = null;

        Debug.Log("Loading (" + type.Name + "): " + path);

        XmlTextReader reader = new XmlTextReader( path );
        XmlSerializer serializer = new  XmlSerializer( type, AdditionalTypes.ToArray() );
        thing = serializer.Deserialize( reader );
        reader.Close();

        return( thing );
    }
示例#20
0
    public static XmlDocument LoadAndValidateXml(string xmlFilename, TextAsset schemaFile, ValidationEventHandler validationEventHandler)
    {
        XmlTextReader textReader = null;
        XmlReader validatingReader = null;

        MemoryStream fs = null;
        try
        {
            textReader = new XmlTextReader(xmlFilename);
            XmlReaderSettings readerSettings = new XmlReaderSettings();
            readerSettings.ValidationType = ValidationType.Schema;
            readerSettings.ValidationEventHandler += validationEventHandler;

            fs = new MemoryStream(Encoding.ASCII.GetBytes(schemaFile.text));
            XmlSchema schema = XmlSchema.Read(fs, validationEventHandler);
            readerSettings.Schemas.Add(schema);

            validatingReader = XmlReader.Create(textReader, readerSettings); //new XmlValidatingReader(textReader);

            XmlDocument result = new XmlDocument();
            result.Load(validatingReader);

            Debug.Log("XML validation finished for " + xmlFilename + "!");

            fs.Close();
            validatingReader.Close();
            textReader.Close();

            return result;
        }
        catch (FileNotFoundException e)
        {
            Debug.LogWarning("Could not find file: " + e.FileName);
            if(fs != null) fs.Close();
            if(validatingReader != null) validatingReader.Close();
            if(textReader != null) textReader.Close();
            return null;
        }
    }
示例#21
0
 public bool LoadCharacters()
 {
     Character chart = null;
     if (File.Exists(file))
     {
         XmlTextReader reader = new XmlTextReader(file);
         while (reader.Read())
         {
             switch (reader.Name.ToString().ToLower())
             {
                 case "character": //assuming there is more than one chart
                     chart = new Character();
                     if (reader.HasAttributes)
                     {
                         while (reader.MoveToNextAttribute())
                         {
                             switch (reader.Name.ToString().ToLower())
                             {
                                 case "id":
                                     chart.id = Convert.ToInt32(reader.Value);
                                     break;
                                 case "name":
                                     chart.name = reader.Value;
                                     break;
                                 case "blocked":
                                     chart.blocked = (Convert.ToInt32(reader.Value) == 1);
                                     break;
                                 case "file":
                                     chart.fileDir = reader.Value;
                                     break;
                                 case "base": //base position declared
                                     string val = reader.Value;
                                     string[] split = val.Split(',');
                                     chart.basePosition = new Vector3(float.Parse(split[0]), float.Parse(split[1]), float.Parse(split[2]));
                                     break;
                             }
                         }
                         //if we get this point, it's mean there is no more attrs to read
                         if (chart != null)
                         {
                             characters.Add(chart);
                         }
                     }
                     break;
             }
         }
         reader.Close();
         loaded = true;
     }
     return loaded;
 }
示例#22
0
    /// <summary>
    /// 参考表单
    /// 同一零件号的第一张工单的编号
    /// 将成为后续工单的参考工单号
    /// djin 2012-06-21
    /// </summary>
    /// <param name="sender"></param>
    public void Create(object sender)
    {
        try
        {
            string sqlText = string.Empty;
            string ConnString = string.Empty;
            XmlTextReader reader = new XmlTextReader(Server.MapPath("Config/properties.config"));
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);//
            reader.Close();//
            ConnString = doc.SelectSingleNode("/configuration/properties/connectionString").InnerText.Trim();

            IList<OrderHead> orderHeadList = (IList<OrderHead>)sender;
            if (orderHeadList != null && orderHeadList.Count > 0)
            {
                string shiftCode = this.ucShift.ShiftCode;
                Shift shift = TheShiftMgr.LoadShift(shiftCode);
                foreach (var item in orderHeadList)
                {
                    item.Shift = shift;
                }
                TheOrderMgr.CreateOrder(orderHeadList, this.CurrentUser.Code);
                var result = (from order in orderHeadList select order.OrderDetails[0].Item.Code).Distinct();

                foreach (var s in result)
                {
                    var _ordNo = (from order in orderHeadList
                                  where order.OrderDetails[0].Item.Code == s
                                  orderby order.WinDate, order.WindowTime
                                  select order.OrderNo);
                    int i = 0;
                    string refOrderNo = string.Empty;
                    foreach (var ord in _ordNo)
                    {

                        UpdateOrderMstr(ord, refOrderNo, ConnString);
                        if (i == 0) refOrderNo = ord;

                        i++;
                    }
                }

                ShowSuccessMessage("Common.Business.Result.Insert.Successfully");
            }
        }
        catch (BusinessErrorException ex)
        {
            ShowErrorMessage(ex);
        }
    }
示例#23
0
    // To check existing profiles in the profile folder.
    public bool ProfileExists(string profileName)
    {
        // Iterate through profile files
        mySerialize = new XmlSerializer(typeof(Profile));
        DirectoryInfo getDir = new DirectoryInfo(profilePath);
        files = getDir.GetFiles("*.dat");
        if (files.Length>0)
        {
            foreach (FileInfo f in files)
            {
                myReader = new XmlTextReader(profilePath + f.Name);
                Profile p = (Profile)mySerialize.Deserialize(myReader);
                if ((profileName).ToUpper() == p.ProfileName.ToUpper())
                {
                    myReader.Close();
                    return true;
                }
                myReader.Close();
            }
        }

        return false;
    }
示例#24
0
    public static Messages GetInstance()
    {
        string baseDir = AppDomain.CurrentDomain.BaseDirectory;
        string fn = (HttpContext.Current != null) && (HttpContext.Current.Request.MapPath("~/App_Data/") != null) ?
            HttpContext.Current.Request.MapPath("~/App_Data/") + Filename :
            baseDir.Substring(0, baseDir.IndexOf("ProjectsApp") + 11) + "\\ProjectsApp\\App_Data\\" + Filename;
        if (mInstance == null || (File.Exists(fn) && File.GetLastWriteTime(fn) != LastWriteTime))
        {

            XmlSerializer serializer = new XmlSerializer(typeof(Messages));
            Stream stream = null;

            try
            {
                // check App_Data folder
                if (File.Exists(fn))
                {
                    stream = new FileStream(fn, FileMode.Open, FileAccess.Read);
                }
                // if nothing found previously do load default values from executing assembly
                if (stream == null)
                {
                    var assembly = Assembly.GetExecutingAssembly();
                    string FileNS = assembly.FullName.Split(new[] { ',' })[0];
                    stream = assembly.GetManifestResourceStream(FileNS + "." + Filename);
                }

                if (stream == null)
                {
                    throw new Exception(Filename + " not found");
                }
                XmlTextReader reader = new XmlTextReader(stream);
                try
                {
                    mInstance = (Messages)serializer.Deserialize(reader);
                }
                finally
                {
                    reader.Close();
                }
                LastWriteTime = File.GetLastWriteTime(fn);
            }
            finally
            {
                try { if (stream != null) stream.Close(); }
                catch { }
            }
        }
        return mInstance;
    }
    public string Delete(string id_delete)
    {
        HttpContext.Current.Session["id_delete"] = id_delete;
        string str = "";
        string[] id = new string[50];
        if (id_delete.Length > 0)
        {
            try
            {
                string str_where = id_delete.Substring(0, id_delete.Length - 1);
                id = str_where.Split(',');

                string file_name = HttpContext.Current.Session["language_code_file"].ToString();
                XmlTextReader reader = new XmlTextReader(file_name);
                XmlDocument doc = new XmlDocument();
                doc.Load(reader);
                reader.Close();

                //Select the cd node with the matching title
                XmlNode cd;
                XmlElement root = doc.DocumentElement;
                for (int i = 0; i < id.Length; i++)
                {
                    cd = root.SelectSingleNode("/language_code/code[key='" + id[i] + "']");
                    if (cd != null)
                    {
                        root.RemoveChild(cd);
                    }
                    //save the output to a file
                }
                doc.Save(file_name);
                str = "";
                HttpContext.Current.Application["nav_language_code"] = null;
                SetApp();
            }
            catch (Exception ex)
            {
                //Response.Write(ex.ToString());
                str = "Quyền cập nhập file đã khóa. Không thể xóa bỏ. ";
            }
        }
        else
        {
            str = "Bạn phải chọn dữ liệu muốn xóa";
        }
        return str;
    }
示例#26
0
  public static void Main()  
  {
     XmlTextReader xtr = new XmlTextReader(@"c:\Videos.xml");

     xtr.WhitespaceHandling = WhitespaceHandling.All;

     //Parse the file and display each of the nodes.
     while (xtr.Read())
     {
        switch (xtr.NodeType)
        {
          case XmlNodeType.Element:
            Console.Write("<{0}>", xtr.Name);
            break;
          case XmlNodeType.Text:
            Console.Write(xtr.Value);
            break;
          case XmlNodeType.CDATA:
            Console.Write("<![CDATA[{0}]]>", xtr.Value);
            break;
          case XmlNodeType.ProcessingInstruction:
            Console.Write("<?{0} {1}?>", xtr.Name, xtr.Value);
            break;
          case XmlNodeType.Comment:
            Console.Write("<!--{0}-->", xtr.Value);
            break;
          case XmlNodeType.XmlDeclaration:
            Console.Write("<?xml version='1.0'?>");
            break;
          case XmlNodeType.DocumentType:
            Console.Write("<!DOCTYPE {0} [{1}]", xtr.Name, xtr.Value);
            break;
          case XmlNodeType.EntityReference:
            Console.Write(xtr.Name);
            break;
          case XmlNodeType.EndElement:
            Console.Write("</{0}>", xtr.Name);
            break;
          case XmlNodeType.Whitespace:
            Console.Write("{0}", xtr.Value );
            break;
        }       
     }           

     if ( xtr != null)
         xtr.Close();
  } 
示例#27
0
    //Load XML including tag name node from local file
    public List<string>LoadXmlFromFile( string filename, string tagName )
    {
        XmlNodeList elemList = null;
        var doc = new XmlDocument ();
        XmlTextReader reader = new XmlTextReader(filename);
        List<string> strList = new List<string>();

        doc.Load (reader);

        elemList = GetXmlElems (doc, tagName);

        strList = ConvertElemsToList (elemList);

        reader.Close ();

        return strList;
    }
示例#28
0
        private void LoadSchemaFromLocation(string uri)
        {
            // is x-schema
            if (!XdrBuilder.IsXdrSchema(uri))
            {
                return;
            }
            string     url       = uri.Substring(x_schema.Length);
            XmlReader? reader    = null;
            SchemaInfo?xdrSchema = null;

            try
            {
                Uri    ruri = this.XmlResolver !.ResolveUri(BaseUri, url);
                Stream stm  = (Stream)this.XmlResolver.GetEntity(ruri, null, null) !;
                reader = new XmlTextReader(ruri.ToString(), stm, NameTable);
                ((XmlTextReader)reader).XmlResolver = this.XmlResolver;
                Parser parser = new Parser(SchemaType.XDR, NameTable, SchemaNames, EventHandler);
                parser.XmlResolver = this.XmlResolver;
                parser.Parse(reader, uri);
                while (reader.Read())
                {
                    ;                   // wellformness check
                }
                xdrSchema = parser.XdrSchema;
            }
            catch (XmlSchemaException e)
            {
                SendValidationEvent(SR.Sch_CannotLoadSchema, new string[] { uri, e.Message }, XmlSeverityType.Error);
            }
            catch (Exception e)
            {
                SendValidationEvent(SR.Sch_CannotLoadSchema, new string[] { uri, e.Message }, XmlSeverityType.Warning);
            }
            finally
            {
                reader?.Close();
            }
            if (xdrSchema != null && xdrSchema.ErrorCount == 0)
            {
                schemaInfo !.Add(xdrSchema, EventHandler);
                SchemaCollection !.Add(uri, xdrSchema, null, false);
            }
        }
示例#29
0
	public static void TestDir (string masterlist, TextWriter w)
	{
		FileInfo fi = new FileInfo (masterlist);
		string dirname = fi.Directory.Parent.FullName;

		SchemaDumper d = new SchemaDumper (w);
#if false
		foreach (DirectoryInfo di in new DirectoryInfo (dirname).GetDirectories ())
			foreach (FileInfo fi in di.GetFiles ("*.xsd")) {
				try {
					d.IndentLine ("**** File : " + fi.Name);
					d.DumpSchema (XmlSchema.Read (new XmlTextReader (fi.FullName), null));
				} catch (Exception ex) {
					d.IndentLine ("**** Error in " + fi.Name);
				}
			}
#else
		XmlDocument doc = new XmlDocument ();
		doc.Load (fi.FullName);

		foreach (XmlElement test in doc.SelectNodes ("/tests/test")) {
			// Test schema
			string schemaFile = test.SelectSingleNode ("@schema").InnerText;
			if (schemaFile.Length > 2)
				schemaFile = schemaFile.Substring (2);
			bool isValidSchema = test.SelectSingleNode ("@out_s").InnerText == "1";

			if (!isValidSchema)
				continue;
#endif
			try {
				d.IndentLine ("**** File : " + schemaFile);
				d.depth++;
				XmlTextReader xtr = new XmlTextReader (dirname + "/" + schemaFile);
				d.DumpSchema (XmlSchema.Read (xtr, null));
				xtr.Close ();
			} catch (Exception ex) {
				d.IndentLine ("**** Error in " + schemaFile);
			} finally {
				d.depth--;
			}
		}
	}
示例#30
0
        public List <User> XMLToUsers(string xml)
        {
            StringReader  strReader = null;
            XmlTextReader xmlReader = null;
            Object        obj       = null;

            try
            {
                strReader = new StringReader(xml);
                var serializer = new XmlSerializer(typeof(List <User>));
                xmlReader = new XmlTextReader(strReader);
                obj       = serializer.Deserialize(xmlReader);
            }
            catch (Exception) { }
            finally
            {
                xmlReader?.Close();
                strReader?.Close();
            }
            return((List <User>)obj);
        }
        /// <summary>
        /// 将XML字符创转换为DataSet
        /// </summary>
        /// <param name="xmlData">XML字符</param>
        /// <returns>DataSet:相同结点生成一个DataTable</returns>
        public static DataSet XmlToDataSet(string xmlData)
        {
            XmlTextReader reader = null;

            try
            {
                DataSet      xmlDs  = new DataSet();
                StringReader stream = new StringReader(xmlData);
                reader = new XmlTextReader(stream);
                xmlDs.ReadXml(reader);
                return(xmlDs);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                reader?.Close();
            }
        }
示例#32
0
    private static void InitializeData()
    {
        _zips = new BitArray(100000, false);
        _locations = new Dictionary<string, string[]>(1000);

        XmlTextReader reader = null;

        try
        {
            reader = new XmlTextReader(HttpContext.Current.Server.MapPath("~/App_Data/ZipCodes.xml"));
            reader.WhitespaceHandling = WhitespaceHandling.None;

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "City")
                {
                    reader.Read();
                    string city = reader.Value;     // Read city name
                    reader.Read();
                    reader.Read();
                    reader.Read();
                    string state = reader.Value;    // Read state name
                    reader.Read();
                    reader.Read();
                    reader.Read();
                    string zip = reader.Value;      // Read zip code

                    _zips[Convert.ToInt32(zip)] = true;
                    _locations.Add(zip, new string[2] { city, state });
                }
            }

            _initialized = true;
        }
        finally
        {
            if (reader != null)
                reader.Close();
        }
    }
示例#33
0
    public static string ReadXML(string xmlFileNameWPath, string xPath)
    {
        string RetVal = string.Empty;

        XmlNode xmlNode = null;
        XmlElement Element = null;
        XmlElement root = null;
        XmlDocument doc = null;
        XmlTextReader reader = null;

        try
        {
            //load document at once
            reader = new XmlTextReader(xmlFileNameWPath);
            doc = new XmlDocument();
            doc.Load(reader);
            reader.Close();

            root = doc.DocumentElement;
            if (!string.IsNullOrEmpty(xPath))
            {
                xmlNode = root.SelectSingleNode(xPath);
                if (xmlNode != null)
                {
                    RetVal = xmlNode.InnerXml;
                }
            }
            else
            {
                RetVal = doc.InnerXml;
            }
        }
        catch (Exception ex)
        {
            throw;
        }

        return RetVal;
    }
示例#34
0
        public List <UsersLogin> GetLoginsFromXML()
        {
            var               xml       = File.ReadAllText("login.xml");
            StringReader      strReader = null;
            XmlTextReader     xmlReader = null;
            List <UsersLogin> obj       = null;

            try
            {
                strReader = new StringReader(xml);
                var serializer = new XmlSerializer(typeof(List <UsersLogin>));
                xmlReader = new XmlTextReader(strReader);
                obj       = (List <UsersLogin>)serializer.Deserialize(xmlReader);
            }
            catch (Exception) { }
            finally
            {
                xmlReader?.Close();
                strReader?.Close();
            }
            return(obj ?? new List <UsersLogin>());
        }
示例#35
0
        /// <summary>
        /// Read the .config from a file.
        /// </summary>
        /// <param name="appConfigFile"></param>
        internal void Load(string appConfigFile)
        {
            XmlTextReader reader = null;

            try
            {
                reader = new XmlTextReader(appConfigFile);
                reader.DtdProcessing = DtdProcessing.Ignore;
                Read(reader);
            }
            catch (XmlException e)
            {
                throw new AppConfigException(e.Message, appConfigFile, (reader != null ? reader.LineNumber : 0), (reader != null ? reader.LinePosition : 0), e);
            }
            catch (Exception e) when(ExceptionHandling.IsIoRelatedException(e))
            {
                throw new AppConfigException(e.Message, appConfigFile, (reader != null ? reader.LineNumber : 0), (reader != null ? reader.LinePosition : 0), e);
            }
            finally
            {
                reader?.Close();
            }
        }
示例#36
0
        public static object XmlToObjects(string xml, Type object_type)
        {
            StringReader  str_reader = null;
            XmlTextReader xml_reader = null;
            object        obj;

            try {
                str_reader = new StringReader(xml);
                var serializer = new XmlSerializer(object_type);
                xml_reader = new XmlTextReader(str_reader);
                obj        = serializer.Deserialize(xml_reader);
            }
            catch (Exception e) {
                Console.WriteLine(e);
                throw;
            }
            finally {
                xml_reader?.Close();
                str_reader?.Close();
            }

            return(obj);
        }
示例#37
0
        static void ReadXML(string file)
        {
            XmlTextReader reader = null;

            try
            {
                reader = new XmlTextReader(file);
                reader.WhitespaceHandling = WhitespaceHandling.None;
                while (reader.Read())
                {
                    // if (!string.IsNullOrWhiteSpace(reader.Value))
                    {
                        Console.WriteLine($"NodeType={reader.NodeType}\t\t" +
                                          $"Name={reader.Name}\t\t" +
                                          $"Value={reader.Value}");
                    }
                    if (reader.AttributeCount > 0)
                    {
                        while (reader.MoveToNextAttribute())
                        {
                            Console.WriteLine($"" +
                                              $"NodeType={reader.NodeType}\t\t" +
                                              $"Name={reader.Name}\t\t" +
                                              $"Value={reader.Value}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                reader?.Close();
            }
        }
        public static object ObjectToXML(string xml, Type objectType)
        {
            StringReader  strReader = null;
            XmlTextReader xmlReader = null;
            object        obj       = null;

            try
            {
                strReader = new StringReader(xml);
                var serializer = new XmlSerializer(objectType);
                xmlReader = new XmlTextReader(strReader);
                obj       = serializer.Deserialize(xmlReader);
            }
            catch (Exception)
            {
                //Handle Exception Code
            }
            finally
            {
                xmlReader?.Close();
                strReader?.Close();
            }
            return(obj);
        }
示例#39
0
        public List <Package> XMLToPackages()
        {
            var           xml       = File.ReadAllText("packages.xml");
            StringReader  strReader = null;
            XmlTextReader xmlReader = null;
            Object        obj       = null;

            try
            {
                strReader = new StringReader(xml);
                var serializer = new XmlSerializer(typeof(List <Package>));
                xmlReader = new XmlTextReader(strReader);
                obj       = serializer.Deserialize(xmlReader);
            }
            catch (Exception) { }
            finally
            {
                xmlReader?.Close();
                strReader?.Close();
            }

            obj = obj ?? new List <Package>();
            return((List <Package>)obj);
        }
示例#40
0
        /// <summary>
        /// Gets the XML schemas for generating data contracts.
        /// </summary>
        /// <param name="options">The metadata resolving options.</param>
        /// <returns>A collection of the XML schemas.</returns>
        public static XmlSchemas GetXmlSchemaSetFromDataContractFiles(MetadataResolverOptions options)
        {
            if (options.DataContractFiles == null)
            {
                throw new ArgumentNullException("No data contract files provided");
            }

            // Resolve the schemas.
            XmlSchemaSet schemaSet = CreateXmlSchemaSet();

            for (int fi = 0; fi < options.DataContractFiles.Length; fi++)
            {
                // Skip the non xsd/wsdl files.
                string lowext = Path.GetExtension(options.DataContractFiles[fi]).ToLower();
                if (lowext == ".xsd") // This is an XSD file.
                {
                    XmlTextReader xmltextreader = null;

                    try
                    {
                        xmltextreader = new XmlTextReader(options.DataContractFiles[fi]);
                        XmlSchema schema = XmlSchema.Read(xmltextreader, null);
                        if (options.GenerateSeparateFilesEachXsd)
                        {
                            if (string.IsNullOrWhiteSpace(schema.SourceUri))
                            {
                                schema.SourceUri = options.DataContractFiles[fi];
                            }
                            ResolveIncludedSchemas(schemaSet, schema);
                        }
                        schemaSet.Add(schema);
                    }
                    finally
                    {
                        if (xmltextreader != null)
                        {
                            xmltextreader.Close();
                        }
                    }
                }
                else if (lowext == ".wsdl") // This is a WSDL file.
                {
                    AntDiscoveryClientProtocol dcp = new AntDiscoveryClientProtocol();
                    dcp.AllowAutoRedirect = true;
                    dcp.Credentials       = CredentialCache.DefaultCredentials;
                    dcp.DiscoverAny(options.DataContractFiles[fi]);
                    dcp.ResolveAll();
                    foreach (string url in dcp.Documents.Keys)
                    {
                        object document = dcp.Documents[url];
                        if (document is XmlSchema)
                        {
                            XmlSchema xmlSchema = (XmlSchema)document;
                            if (options.GenerateSeparateFilesEachXsd)
                            {
                                if (string.IsNullOrWhiteSpace(xmlSchema.SourceUri))
                                {
                                    xmlSchema.SourceUri = url;
                                }
                                ResolveIncludedSchemas(schemaSet, xmlSchema);
                            }
                            schemaSet.Add(xmlSchema);
                        }
                        if (document is WebServiceDescription)
                        {
                            foreach (XmlSchema schema in ((WebServiceDescription)document).Types.Schemas)
                            {
                                if (!IsEmptySchema(schema))
                                {
                                    if (options.GenerateSeparateFilesEachXsd)
                                    {
                                        if (string.IsNullOrWhiteSpace(schema.SourceUri))
                                        {
                                            schema.SourceUri = url;
                                        }
                                        ResolveIncludedSchemas(schemaSet, schema);
                                    }
                                    schemaSet.Add(schema);
                                }
                            }
                        }
                    }
                }
            }

            RemoveDuplicates(ref schemaSet);
            schemaSet.Compile();

            XmlSchemas schemas = new XmlSchemas();

            foreach (XmlSchema schema in schemaSet.Schemas())
            {
                schemas.Add(schema);
            }

            return(schemas);
        }
示例#41
0
        public static void CheckForUpdate(bool startup = false)
        {
            Version newVersion = null;
            bool    betaUpdate = false, requiredUpdate = false;

            string xmlUrl = string.Empty, elementName = string.Empty, mbNewVersion = string.Empty, mbCurrentVersion = string.Empty, mbText = string.Empty;
            string downloadUrl = "https://github.com/tyxman/EduPlanner/releases/";

            string mbHeader = DataManager.APPLICATIONNAME + " Updater";
            string msgError = "An unknown error occured while checking for updates.";

            if (DataManager.Settings.ReceiveBetaUpdates == true)
            {
                //xmlUrl = @"D:\Desktop\update.xml";
                xmlUrl = "https://josephdp.com/eduplanner/updater/beta.xml";
            }

            if (DataManager.Settings.ReceiveBetaUpdates == false)
            {
                //xmlUrl = @"D:\Desktop\update.xml";
                xmlUrl = "https://josephdp.com/eduplanner/updater/stable.xml";
            }

            XmlTextReader reader = new XmlTextReader(xmlUrl);

            try
            {
                // simply (and easily) skip the junk at the beginning
                reader.MoveToContent();

                // internal - as the XmlTextReader moves only
                // forward, we save current xml element name
                // in elementName variable. When we parse a
                // text node, we refer to elementName to check
                // what was the node name

                if (reader.NodeType == XmlNodeType.Element && reader.Name == DataManager.APPLICATIONNAME)
                {
                    while (reader.Read())
                    {
                        // when we find an element node,
                        // we remember its name
                        if (reader.NodeType == XmlNodeType.Element)
                        {
                            elementName = reader.Name;
                        }
                        else
                        {
                            // for text nodes...
                            if (reader.NodeType == XmlNodeType.Text && reader.HasValue)
                            {
                                // we check what the name of the node was
                                switch (elementName)
                                {
                                case "version":
                                    newVersion = new Version(reader.Value);
                                    break;

                                case "url":
                                    downloadUrl = reader.Value;
                                    break;

                                case "beta":
                                    if (reader.Value == "true")
                                    {
                                        betaUpdate = true;
                                    }
                                    break;

                                case "required":
                                    if (reader.Value == "true")
                                    {
                                        requiredUpdate = true;
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    throw new Exception(msgError);
                }

                string[] currentBuild = About.currentVersion.ToString().Split('.');
                if (currentBuild[2] == "0")
                {
                    mbCurrentVersion = About.currentVersion.ToString(2);
                }
                else
                {
                    mbCurrentVersion = string.Format("{0} ({1})", About.currentVersion.ToString(2), currentBuild[2]);
                }

                string[] newBuild = newVersion.ToString().Split('.');
                if (newBuild[2] == "0")
                {
                    mbNewVersion = newVersion.ToString(2);
                }
                else
                {
                    mbNewVersion = string.Format("{0} ({1})", Assembly.GetExecutingAssembly().GetName().Version.ToString(2), newBuild[2]);
                }

                if (About.currentVersion.CompareTo(newVersion) < 0)
                {
                    if (requiredUpdate == true)
                    {
                        mbText = String.Format("New version detected. You must update to continue!\n\n" +
                                               "Current version: {0}\n" +
                                               "New version: {1}", mbCurrentVersion, mbNewVersion);
                        MessageBoxResult result = MessageBox.Show(mbText, mbHeader, MessageBoxButton.OKCancel, MessageBoxImage.Warning);
                        if (result == MessageBoxResult.OK)
                        {
                            using (WebClient wc = new WebClient())
                            {
                                wc.DownloadFileCompleted += InstallUpdate;
                                wc.DownloadFileAsync(new Uri(downloadUrl), "setup.exe");
                            }
                        }
                        if (result == MessageBoxResult.Cancel)
                        {
                            Environment.Exit(0);
                        }
                    }

                    if (requiredUpdate == false && startup == true && DataManager.Settings.CheckForUpdatesOnStartup == true)
                    {
                        if (betaUpdate == true && DataManager.Settings.ReceiveBetaUpdates == true)
                        {
                            BetaUpdateDialog();
                        }
                        if (betaUpdate == false)
                        {
                            UpdateDialog();
                        }
                    }

                    if (startup == false)
                    {
                        if (betaUpdate == true && DataManager.Settings.ReceiveBetaUpdates == true)
                        {
                            BetaUpdateDialog();
                        }
                        if (betaUpdate == false)
                        {
                            UpdateDialog();
                        }

                        if (betaUpdate == true && DataManager.Settings.ReceiveBetaUpdates == false && requiredUpdate == false)
                        {
                            LatestVersionDialog();
                        }
                    }
                }

                else if (About.currentVersion == newVersion && startup == false)
                {
                    LatestVersionDialog();
                }

                else if (About.currentVersion.CompareTo(newVersion) > 0)
                {
                    throw new Exception(msgError);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, mbHeader, MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                reader?.Close();
            }

            void BetaUpdateDialog()
            {
                mbText = String.Format("New version detected. Would you like to download it now?\n\n" +
                                       "Current version: {0}\n" +
                                       "New beta version: {1}", mbCurrentVersion, mbNewVersion);
                MessageBoxResult result = MessageBox.Show(mbText, mbHeader, MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    using (WebClient wc = new WebClient())
                    {
                        wc.DownloadFileCompleted += InstallUpdate;
                        wc.DownloadFileAsync(new Uri(downloadUrl), "setup.exe");
                    }
                }
            }

            void UpdateDialog()
            {
                mbText = String.Format("New version detected. Would you like to download it now?\n\n" +
                                       "Current version: {0}\n" +
                                       "New version: {1}", mbCurrentVersion, mbNewVersion);
                MessageBoxResult result = MessageBox.Show(mbText, mbHeader, MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    using (WebClient wc = new WebClient())
                    {
                        wc.DownloadFileCompleted += InstallUpdate;
                        wc.DownloadFileAsync(new Uri(downloadUrl), "setup.exe");
                    }
                }
            }

            void LatestVersionDialog()
            {
                MessageBox.Show("You are running the latest version of EduPlanner!", mbHeader, MessageBoxButton.OK, MessageBoxImage.Information);
            }

            void InstallUpdate(object sender, AsyncCompletedEventArgs e)
            {
                MessageBoxResult result = MessageBox.Show("EduPlanner will now restart to install an update.", mbHeader, MessageBoxButton.OK, MessageBoxImage.Information);

                if (result == MessageBoxResult.OK)
                {
                    try
                    {
                        System.Diagnostics.Process.Start("setup.exe");
                        Environment.Exit(0);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, mbHeader, MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
        }
示例#42
0
        public bool TryReverseGeocoding()
        {
            bool          isOK   = false;
            XmlTextReader reader = null;

            System.IO.Stream stream = null;
            try
            {
                StringBuilder for_uri = new StringBuilder(100);

                for_uri.Append("https://nominatim.openstreetmap.org/reverse?format=xml");
                for_uri.Append("&lat=");
                for_uri.Append(Latitude.ToString(System.Globalization.CultureInfo.GetCultureInfo("en-US")));
                for_uri.Append("&lon=");
                for_uri.Append(Longitude.ToString(System.Globalization.CultureInfo.GetCultureInfo("en-US")));
                for_uri.Append("&zoom=18&addressdetails=");
                for_uri.Append((details_flag == true) ? "1" : "0");
                for_uri.Append("&[email protected]");

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(for_uri.ToString());
                request.UserAgent = "WhereIsMyPhoto " + Application.ProductVersion.ToString();
                request.Timeout   = 1000;
                WebResponse response = request.GetResponse();

                stream = response.GetResponseStream();

                reader = new XmlTextReader(stream);
                XmlDocument document = new XmlDocument();
                document.Load(reader);
                XmlNode resultNode = document.GetElementsByTagName("result")[0];

                FullInformation = resultNode.InnerText;

                if (details_flag)
                {
                    XmlNode addressparts = document.GetElementsByTagName("addressparts")[0];
                    foreach (XmlNode node in addressparts)
                    {
                        switch (node.Name)
                        {
                        case "house_number":
                            Home = node.InnerText;
                            break;

                        case "road":
                            Street = node.InnerText;
                            break;

                        case "city":
                            City = node.InnerText;
                            break;

                        case "country":
                            Country = node.InnerText;
                            break;
                        }
                    }
                }


                // stream.Close();
                // reader.Close();
                isOK = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                isOK = false;
            }
            finally
            {
                stream?.Close();
                reader?.Close();
            }
            return(isOK);
        }
            public static void LoadFromXml(DockPanel dockPanel, Stream stream, DeserializeDockContent deserializeContent, bool closeStream)
            {
                if (dockPanel.Contents.Count != 0)
                {
                    throw new InvalidOperationException(Strings.DockPanel_LoadFromXml_AlreadyInitialized);
                }

                XmlTextReader xmlIn = new XmlTextReader(stream);

                xmlIn.WhitespaceHandling = WhitespaceHandling.None;
                xmlIn.MoveToContent();

                while (!xmlIn.Name.Equals("DockPanel"))
                {
                    if (!MoveToNextElement(xmlIn))
                    {
                        throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
                    }
                }

                string formatVersion = xmlIn.GetAttribute("FormatVersion");

                if (!IsFormatVersionValid(formatVersion))
                {
                    throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidFormatVersion);
                }

                DockPanelStruct dockPanelStruct = new DockPanelStruct();

                dockPanelStruct.DockLeftPortion         = Convert.ToDouble(xmlIn.GetAttribute("DockLeftPortion"), CultureInfo.InvariantCulture);
                dockPanelStruct.DockRightPortion        = Convert.ToDouble(xmlIn.GetAttribute("DockRightPortion"), CultureInfo.InvariantCulture);
                dockPanelStruct.DockTopPortion          = Convert.ToDouble(xmlIn.GetAttribute("DockTopPortion"), CultureInfo.InvariantCulture);
                dockPanelStruct.DockBottomPortion       = Convert.ToDouble(xmlIn.GetAttribute("DockBottomPortion"), CultureInfo.InvariantCulture);
                dockPanelStruct.IndexActiveDocumentPane = Convert.ToInt32(xmlIn.GetAttribute("ActiveDocumentPane"), CultureInfo.InvariantCulture);
                dockPanelStruct.IndexActivePane         = Convert.ToInt32(xmlIn.GetAttribute("ActivePane"), CultureInfo.InvariantCulture);

                // Load Contents
                MoveToNextElement(xmlIn);
                if (xmlIn.Name != "Contents")
                {
                    throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
                }
                ContentStruct[] contents = LoadContents(xmlIn);

                // Load Panes
                if (xmlIn.Name != "Panes")
                {
                    throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
                }
                PaneStruct[] panes = LoadPanes(xmlIn);

                // Load DockWindows
                if (xmlIn.Name != "DockWindows")
                {
                    throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
                }
                DockWindowStruct[] dockWindows = LoadDockWindows(xmlIn, dockPanel);

                // Load FloatWindows
                if (xmlIn.Name != "FloatWindows")
                {
                    throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
                }
                FloatWindowStruct[] floatWindows = LoadFloatWindows(xmlIn);

                if (closeStream)
                {
                    xmlIn.Close();
                }

                dockPanel.SuspendLayout(true);

                dockPanel.DockLeftPortion   = dockPanelStruct.DockLeftPortion;
                dockPanel.DockRightPortion  = dockPanelStruct.DockRightPortion;
                dockPanel.DockTopPortion    = dockPanelStruct.DockTopPortion;
                dockPanel.DockBottomPortion = dockPanelStruct.DockBottomPortion;

                // Set DockWindow ZOrders
                int prevMaxDockWindowZOrder = int.MaxValue;

                for (int i = 0; i < dockWindows.Length; i++)
                {
                    int maxDockWindowZOrder = -1;
                    int index = -1;
                    for (int j = 0; j < dockWindows.Length; j++)
                    {
                        if (dockWindows[j].ZOrderIndex > maxDockWindowZOrder && dockWindows[j].ZOrderIndex < prevMaxDockWindowZOrder)
                        {
                            maxDockWindowZOrder = dockWindows[j].ZOrderIndex;
                            index = j;
                        }
                    }

                    dockPanel.DockWindows[dockWindows[index].DockState].BringToFront();
                    prevMaxDockWindowZOrder = maxDockWindowZOrder;
                }

                // Create Contents
                for (int i = 0; i < contents.Length; i++)
                {
                    IDockContent content = deserializeContent(contents[i].PersistString);
                    if (content == null)
                    {
                        content = new DummyContent();
                    }
                    content.DockHandler.DockPanel       = dockPanel;
                    content.DockHandler.AutoHidePortion = contents[i].AutoHidePortion;
                    content.DockHandler.IsHidden        = true;
                    content.DockHandler.IsFloat         = contents[i].IsFloat;
                }

                // Create panes
                for (int i = 0; i < panes.Length; i++)
                {
                    DockPane pane = null;
                    for (int j = 0; j < panes[i].IndexContents.Length; j++)
                    {
                        IDockContent content = dockPanel.Contents[panes[i].IndexContents[j]];
                        if (j == 0)
                        {
                            pane = dockPanel.DockPaneFactory.CreateDockPane(content, panes[i].DockState, false);
                        }
                        else if (panes[i].DockState == DockState.Float)
                        {
                            content.DockHandler.FloatPane = pane;
                        }
                        else
                        {
                            content.DockHandler.PanelPane = pane;
                        }
                    }
                }

                // Assign Panes to DockWindows
                for (int i = 0; i < dockWindows.Length; i++)
                {
                    for (int j = 0; j < dockWindows[i].NestedPanes.Length; j++)
                    {
                        DockWindow    dw            = dockPanel.DockWindows[dockWindows[i].DockState];
                        int           indexPane     = dockWindows[i].NestedPanes[j].IndexPane;
                        DockPane      pane          = dockPanel.Panes[indexPane];
                        int           indexPrevPane = dockWindows[i].NestedPanes[j].IndexPrevPane;
                        DockPane      prevPane      = (indexPrevPane == -1) ? dw.NestedPanes.GetDefaultPreviousPane(pane) : dockPanel.Panes[indexPrevPane];
                        DockAlignment alignment     = dockWindows[i].NestedPanes[j].Alignment;
                        double        proportion    = dockWindows[i].NestedPanes[j].Proportion;
                        pane.DockTo(dw, prevPane, alignment, proportion);
                        if (panes[indexPane].DockState == dw.DockState)
                        {
                            panes[indexPane].ZOrderIndex = dockWindows[i].ZOrderIndex;
                        }
                    }
                }

                // Create float windows
                for (int i = 0; i < floatWindows.Length; i++)
                {
                    FloatWindow fw = null;
                    for (int j = 0; j < floatWindows[i].NestedPanes.Length; j++)
                    {
                        int      indexPane = floatWindows[i].NestedPanes[j].IndexPane;
                        DockPane pane      = dockPanel.Panes[indexPane];
                        if (j == 0)
                        {
                            fw = dockPanel.FloatWindowFactory.CreateFloatWindow(dockPanel, pane, floatWindows[i].Bounds);
                        }
                        else
                        {
                            int           indexPrevPane = floatWindows[i].NestedPanes[j].IndexPrevPane;
                            DockPane      prevPane      = indexPrevPane == -1 ? null : dockPanel.Panes[indexPrevPane];
                            DockAlignment alignment     = floatWindows[i].NestedPanes[j].Alignment;
                            double        proportion    = floatWindows[i].NestedPanes[j].Proportion;
                            pane.DockTo(fw, prevPane, alignment, proportion);
                        }

                        if (panes[indexPane].DockState == fw.DockState)
                        {
                            panes[indexPane].ZOrderIndex = floatWindows[i].ZOrderIndex;
                        }
                    }
                }

                // sort IDockContent by its Pane's ZOrder
                int[] sortedContents = null;
                if (contents.Length > 0)
                {
                    sortedContents = new int[contents.Length];
                    for (int i = 0; i < contents.Length; i++)
                    {
                        sortedContents[i] = i;
                    }

                    int lastDocument = contents.Length;
                    for (int i = 0; i < contents.Length - 1; i++)
                    {
                        for (int j = i + 1; j < contents.Length; j++)
                        {
                            DockPane pane1        = dockPanel.Contents[sortedContents[i]].DockHandler.Pane;
                            int      ZOrderIndex1 = pane1 == null ? 0 : panes[dockPanel.Panes.IndexOf(pane1)].ZOrderIndex;
                            DockPane pane2        = dockPanel.Contents[sortedContents[j]].DockHandler.Pane;
                            int      ZOrderIndex2 = pane2 == null ? 0 : panes[dockPanel.Panes.IndexOf(pane2)].ZOrderIndex;
                            if (ZOrderIndex1 > ZOrderIndex2)
                            {
                                int temp = sortedContents[i];
                                sortedContents[i] = sortedContents[j];
                                sortedContents[j] = temp;
                            }
                        }
                    }
                }

                // show non-document IDockContent first to avoid screen flickers
                for (int i = 0; i < contents.Length; i++)
                {
                    IDockContent content = dockPanel.Contents[sortedContents[i]];
                    if (content.DockHandler.Pane != null && content.DockHandler.Pane.DockState != DockState.Document)
                    {
                        content.DockHandler.IsHidden = contents[sortedContents[i]].IsHidden;
                    }
                }

                // after all non-document IDockContent, show document IDockContent
                for (int i = 0; i < contents.Length; i++)
                {
                    IDockContent content = dockPanel.Contents[sortedContents[i]];
                    if (content.DockHandler.Pane != null && content.DockHandler.Pane.DockState == DockState.Document)
                    {
                        content.DockHandler.IsHidden = contents[sortedContents[i]].IsHidden;
                    }
                }

                for (int i = 0; i < panes.Length; i++)
                {
                    dockPanel.Panes[i].ActiveContent = panes[i].IndexActiveContent == -1 ? null : dockPanel.Contents[panes[i].IndexActiveContent];
                }

                if (dockPanelStruct.IndexActiveDocumentPane != -1)
                {
                    dockPanel.Panes[dockPanelStruct.IndexActiveDocumentPane].Activate();
                }

                if (dockPanelStruct.IndexActivePane != -1)
                {
                    dockPanel.Panes[dockPanelStruct.IndexActivePane].Activate();
                }

                for (int i = dockPanel.Contents.Count - 1; i >= 0; i--)
                {
                    if (dockPanel.Contents[i] is DummyContent)
                    {
                        dockPanel.Contents[i].DockHandler.Form.Close();
                    }
                }

                dockPanel.ResumeLayout(true, true);
            }
示例#44
0
            private List <string> load(int max)
            {
                var list = new List <string>(max);

                using (var ms = new MemoryStream())
                {
                    using (var ss = openStream(FileMode.OpenOrCreate))
                    {
                        if (ss.Stream.Length == 0)
                        {
                            return(list);
                        }

                        ss.Stream.Position = 0;

                        var buffer = new byte[1 << 20];
                        for (; ;)
                        {
                            var bytes = ss.Stream.Read(buffer, 0, buffer.Length);
                            if (bytes == 0)
                            {
                                break;
                            }
                            ms.Write(buffer, 0, bytes);
                        }

                        ms.Position = 0;
                    }

                    XmlTextReader x = null;

                    try
                    {
                        x = new XmlTextReader(ms);

                        while (x.Read())
                        {
                            switch (x.NodeType)
                            {
                            case XmlNodeType.XmlDeclaration:
                            case XmlNodeType.Whitespace:
                                break;

                            case XmlNodeType.Element:
                                switch (x.Name)
                                {
                                case "RecentFiles": break;

                                case "RecentFile":
                                    if (list.Count < max)
                                    {
                                        list.Add(x.GetAttribute(0));
                                    }
                                    break;

// ReSharper disable HeuristicUnreachableCode
                                default: Debug.Assert(false); break;
// ReSharper restore HeuristicUnreachableCode
                                }
                                break;

                            case XmlNodeType.EndElement:
                                switch (x.Name)
                                {
                                case "RecentFiles": return(list);

// ReSharper disable HeuristicUnreachableCode
                                default: Debug.Assert(false); break;
// ReSharper restore HeuristicUnreachableCode
                                }
// ReSharper disable HeuristicUnreachableCode
                                break;
// ReSharper restore HeuristicUnreachableCode

                            default:
                                Debug.Assert(false);
// ReSharper disable HeuristicUnreachableCode
                                break;
// ReSharper restore HeuristicUnreachableCode
                            }
                        }
                    }
                    finally
                    {
                        x?.Close();
                    }
                }
                return(list);
            }
示例#45
0
        public bool config_load(string _cfg, int _modo)
        {
            string        text   = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\" + _cfg;
            XmlTextReader reader = null;

            if (_log != null)
            {
                _log.Log("Load config (" + _cfg + ")", LogFile.LogLevel.Debug);
            }
            if (Seguridad && _modo == 0 && !HashFile_Load(text))
            {
                if (_log != null)
                {
                    _log.Log("Hash error config (" + _cfg + ")", LogFile.LogLevel.Debug);
                }
                return(false);
            }
            try
            {
                reader = ((_modo != 0) ? new XmlTextReader(new StringReader(_cfg)) : new XmlTextReader(text));
                reader.Read();
                reader.Close();
            }
            catch (Exception ex)
            {
                if (_log != null)
                {
                    _log.Log("XML error config (" + ex.Message + ")", LogFile.LogLevel.Debug);
                }
                reader?.Close();
                return(false);
            }
            try
            {
                reader = ((_modo != 0) ? new XmlTextReader(new StringReader(_cfg)) : new XmlTextReader(text));
            }
            catch (Exception ex)
            {
                error = ex.Message;
                if (_log != null)
                {
                    _log.Log("XML error config (" + ex.Message + ")", LogFile.LogLevel.Debug);
                }
                reader.Close();
                return(false);
            }
            try
            {
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        if (reader.Name.ToLower() == "localize".ToLower() && reader.HasAttributes)
                        {
                            for (int i = 0; i < reader.AttributeCount; i++)
                            {
                                reader.MoveToAttribute(i);
                                if (reader.Name.ToLower() == "language".ToLower())
                                {
                                    try
                                    {
                                        loc = reader.Value.ToString();
                                    }
                                    catch
                                    {
                                    }
                                }
                            }
                        }
                        load(ref reader);
                    }
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                error = ex.Message;
                if (_log != null)
                {
                    _log.Log("XML error config (" + ex.Message + ")", LogFile.LogLevel.Debug);
                }
                reader?.Close();
                return(false);
            }
            if (_log != null)
            {
                _log.Log("Load OK config (" + _cfg + ")", LogFile.LogLevel.Debug);
            }
            return(true);
        }
示例#46
0
 public static FileGroup OpenFile(string filename)
 {
     using (Helpers.Timer("reading {0}", filename))
     {
         XmlDocument   xmlDocument   = new XmlDocument();
         XmlTextReader xmlTextReader = null;
         XmlNode       topNode;
         try
         {
             xmlTextReader = new XmlTextReader(filename);
             xmlTextReader.WhitespaceHandling = WhitespaceHandling.None;
             xmlTextReader.MoveToContent();
             topNode = xmlDocument.ReadNode(xmlTextReader);
         }
         catch (Exception ex)
         {
             FormTools.ErrorDialog(ex.Message);
             return(null);
         }
         finally
         {
             xmlTextReader?.Close();
         }
         if (topNode == null)
         {
             throw new FileLoadException(filename + ": File format error");
         }
         FileGroup fileGroup  = new FileGroup(filename);
         FileGroup fileGroup2 = (from f in ServerTree.Instance.Nodes.OfType <FileGroup>()
                                 where f.Pathname.Equals(fileGroup.Pathname, StringComparison.OrdinalIgnoreCase)
                                 select f).FirstOrDefault();
         if (fileGroup2 == null)
         {
             try
             {
                 List <string> errors = new List <string>();
                 ServerTree.Instance.Operation((OperationBehavior)31, delegate
                 {
                     ServerTree.Instance.AddNode(fileGroup, ServerTree.Instance.RootNode);
                     if (!ReadXml(topNode, fileGroup, errors))
                     {
                         throw new Exception(string.Empty);
                     }
                 });
                 if (errors.Count > 0)
                 {
                     StringBuilder stringBuilder = new StringBuilder("The following errors were encountered:").AppendLine().AppendLine();
                     foreach (string item in errors)
                     {
                         stringBuilder.AppendLine(item);
                     }
                     stringBuilder.AppendLine().Append("The file was not loaded completely. If it is saved it almost certainly means losing information. Continue?");
                     DialogResult dialogResult = FormTools.ExclamationDialog(stringBuilder.ToString(), MessageBoxButtons.YesNo);
                     if (dialogResult == DialogResult.No)
                     {
                         throw new Exception(string.Empty);
                     }
                 }
                 using (Helpers.Timer("sorting root, builtin groups and file"))
                 {
                     ServerTree.Instance.SortRoot();
                     foreach (GroupBase builtInVirtualGroup in Program.BuiltInVirtualGroups)
                     {
                         ServerTree.Instance.SortGroup(builtInVirtualGroup);
                         ServerTree.Instance.OnGroupChanged(builtInVirtualGroup, ChangeType.TreeChanged);
                     }
                     ServerTree.Instance.SortGroup(fileGroup, recurse: true);
                     ServerTree.Instance.OnGroupChanged(fileGroup, ChangeType.TreeChanged);
                 }
                 SmartGroup.RefreshAll(fileGroup);
                 fileGroup.VisitNodes(delegate(RdcTreeNode node)
                 {
                     GroupBase groupBase = node as GroupBase;
                     if (groupBase != null && groupBase.Properties.Expanded.Value)
                     {
                         groupBase.Expand();
                     }
                 });
                 Encryption.DecryptPasswords();
                 fileGroup.CheckCredentials();
                 fileGroup.VisitNodes(delegate(RdcTreeNode n)
                 {
                     n.ResetInheritance();
                 });
                 fileGroup.HasChangedSinceWrite = false;
                 Program.Preferences.NeedToSave = true;
                 return(fileGroup);
             }
             catch (Exception ex2)
             {
                 if (!string.IsNullOrEmpty(ex2.Message))
                 {
                     FormTools.ErrorDialog(ex2.Message);
                 }
                 ServerTree.Instance.RemoveNode(fileGroup);
                 return(null);
             }
         }
         FormTools.InformationDialog("{0} is already open as '{1}'".CultureFormat(fileGroup.Pathname, fileGroup2.Text));
         return(fileGroup2);
     }
 }
    public string DeleteLanguage(string id_delete)
    {
        XPathNodeIterator nodes;
        Language          language_support = new Language();

        language_support.SetFile(HttpContext.Current.Session["language_support"].ToString());
        string files_language = "";

        HttpContext.Current.Session["id_lang_delete"] = id_delete;
        string str = "";

        string[] id = new string[50];
        if (id_delete.Length > 0)
        {
            try
            {
                //if (DeleteFile())
                //{

                string str_where = id_delete.Substring(0, id_delete.Length - 1);
                id = str_where.Split(',');

                string        file_name = HttpContext.Current.Session["language_support"].ToString();
                XmlTextReader reader    = new XmlTextReader(file_name);
                XmlDocument   doc       = new XmlDocument();
                doc.Load(reader);
                reader.Close();


                //Select the cd node with id
                XmlNode           cd;
                XmlElement        root = doc.DocumentElement;
                XPathNavigator    nav  = doc.CreateNavigator();
                XPathNodeIterator iterator;
                for (int i = 0; i < id.Length; i++)
                {
                    iterator = nav.Select("/lang_support/lang[id=" + id[i].ToString() + "]/url");
                    iterator.MoveNext();
                    files_language = iterator.Current.Value;
                    //nodes = language_support.GetLanguageById(id[i].ToString());
                    //while (nodes.MoveNext())
                    //{
                    //    nodes.Current.MoveToFirstChild();
                    //    nodes.Current.MoveToNext();
                    //    nodes.Current.MoveToNext();
                    //    nodes.Current.MoveToNext();
                    //    files_language =nodes.Current.ToString(); //+ ",";
                    //}

                    cd = root.SelectSingleNode("/lang_support/lang[id='" + id[i] + "']");
                    if (cd != null)
                    {
                        root.RemoveChild(cd);
                        File.Delete(HttpContext.Current.Session["path_data"].ToString() + files_language);
                        //save the output to a file
                        doc.Save(file_name);
                        str = "";
                    }
                }
                //HttpContext.Current.Session["file_language"] = files_language;
                //}
            }
            catch (Exception)
            {
                str = "Quyền cập nhật file bị khóa. Không thể xóa bỏ.";
                //Response.Write(ex.ToString());
            }
        }
        else
        {
            str = "Bạn phải chọn dữ liệu muốn xóa !";
        }
        return(str);
    }
示例#48
0
        private void checkForUpdatesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // in newVersion variable we will store the
            // version info from xml file
            Version newVersion = null;
            // and in this variable we will put the url we
            // would like to open so that the user can
            // download the new version
            // it can be a homepage or a direct
            // link to zip/exe file
            var           url    = "";
            XmlTextReader reader = null;

            try
            {
                // provide the XmlTextReader with the URL of
                // our xml document
                var xmlURL = "https://dl.dropboxusercontent.com/u/30305604/winvlfversion.xml";
                reader = new XmlTextReader(xmlURL);
                // simply (and easily) skip the junk at the beginning
                reader.MoveToContent();
                // internal - as the XmlTextReader moves only
                // forward, we save current xml element name
                // in elementName variable. When we parse a
                // text node, we refer to elementName to check
                // what was the node name
                var elementName = "";
                // we check if the xml starts with a proper
                // "ourfancyapp" element node
                if ((reader.NodeType == XmlNodeType.Element) &&
                    (reader.Name == "winvlf"))
                {
                    while (reader.Read())
                    {
                        // when we find an element node,
                        // we remember its name
                        if (reader.NodeType == XmlNodeType.Element)
                        {
                            elementName = reader.Name;
                        }
                        else
                        {
                            // for text nodes...
                            if ((reader.NodeType != XmlNodeType.Text) || (!reader.HasValue))
                            {
                                continue;
                            }
                            // we check what the name of the node was
                            switch (elementName)
                            {
                            case "version":
                                // thats why we keep the version info
                                // in xxx.xxx.xxx.xxx format
                                // the Version class does the
                                // parsing for us
                                newVersion = new Version(reader.Value);
                                break;

                            case "url":
                                url = reader.Value;
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show(@"Server could not be reached", @"Server unreachable", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
                // ignored
            }
            finally
            {
                reader?.Close();
            }

            // get the running version
            var curVersion =
                System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

            // compare the versions
            if (curVersion.CompareTo(newVersion) < 0)
            {
                // ask the user if he would like
                // to download the new version
                const string title    = "New version detected.";
                const string question = "Download the new version?";
                if (DialogResult.Yes ==
                    MessageBox.Show(this, question, title,
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question))
                {
                    // navigate the default web
                    // browser to our app
                    // homepage (the url
                    // comes from the xml content)
                    Process.Start(url);
                }
            }
            else
            {
                MessageBox.Show(this, @"This version is the latest.", @"Latest Version", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
        }
示例#49
0
	public void DumpXmlToArray (string filename)
	{
		XmlTextReader reader = new XmlTextReader (filename);
		reader.WhitespaceHandling = WhitespaceHandling.None;

		int i = 0;
		while (reader.Read ()) {

			switch (reader.NodeType) {

			case XmlNodeType.Element :
				if (reader.Name == "album") {
					reader.MoveToNextAttribute ();
					album_name = reader.Value;
					reader.MoveToNextAttribute ();
					picture_count = Convert.ToInt64 (reader.Value);
				}
				
				break;
				
			case XmlNodeType.Text :
				if (reader.Name == "location")
					picture_data [i].Location = reader.Value;

				if (reader.Name == "title")
					picture_data [i].Title = reader.Value;

				if (reader.Name == "date")
					picture_data [i].Date = reader.Value;

				if (reader.Name == "keywords")
					picture_data [i].Keywords = reader.Value;

				if (reader.Name == "comments")
					picture_data [i].Comments = reader.Value;

				if (reader.Name == "index")
					picture_data [i].Index = Convert.ToInt64 (reader.Value);
				
			case XmlNodeType.EndElement :
				if (reader.Name == "picture") {
					i++;
					picture_data [i] = new PictureInfo ();
				}
				
				break;
				
			default :
				continue;
				break;
			}
		}

		reader.Close ();
	}
示例#50
0
        internal ModuleRuntimeSettings LoadRuntimeProperties()
        {
            string path = configPhysicalFileLocation + "/Module_" + moduleReference + ".config";

            //string mrs = "ModuleRuntimeSettings_" + path;

            if (File.Exists(path))
            {
                // Lookup in Cache
                //moduleRuntimeSettings = (ModuleRuntimeSettings)HttpContext.Current.Cache[mrs];
                //if (moduleRuntimeSettings != null) return;

                XmlTextReader xmlReader = new XmlTextReader(path);
                try
                {
                    moduleRuntimeSettings =
                        (ModuleRuntimeSettings)ModuleRuntimeSettings.xmlModuleSettings.Deserialize(xmlReader);
                }
                finally
                {
                    xmlReader.Close();
                }
            }
            else
            {
                // Config file is not existed. Create new config File
                // Attemp to load Module Settings
                LoadModuleSettings();
                moduleRuntimeSettings = new ModuleRuntimeSettings();
                if (moduleSettings != null)
                {
                    // Read Declared Properties
                    foreach (
                        ModulePropertyDeclaration _objPropertyDeclaration in
                        moduleSettings.ClientRuntimeDefinedProperties)
                    {
                        moduleRuntimeSettings.ClientRuntimeProperties.Add(
                            new ModuleProperty(_objPropertyDeclaration.Name, ""));
                    }
                    foreach (
                        ModulePropertyDeclaration _objPropertyDeclaration in
                        moduleSettings.AdminRuntimeDefinedProperties)
                    {
                        moduleRuntimeSettings.AdminRuntimeProperties.Add(
                            new ModuleProperty(_objPropertyDeclaration.Name, ""));
                    }

                    // Save Module Runtime Settings

                    //XmlTextWriter _objXmlWriter = new XmlTextWriter(path, System.Text.Encoding.UTF8);
                    //_objXmlWriter.Formatting = Formatting.Indented;
                    //try
                    //{
                    //    ModuleRuntimeSettings.xmlModuleSettings.Serialize(_objXmlWriter, moduleRuntimeSettings);
                    //}
                    //finally
                    //{
                    //    _objXmlWriter.Close();
                    //}
                }
            }

            return(moduleRuntimeSettings);
        }
示例#51
0
 private bool LoadSchema(string uri)
 {
     if (_xmlResolver == null)
     {
         return false;
     }
     uri = _NameTable.Add(uri);
     if (_SchemaInfo.TargetNamespaces.ContainsKey(uri))
     {
         return false;
     }
     SchemaInfo schemaInfo = null;
     Uri _baseUri = _xmlResolver.ResolveUri(null, _reader.BaseURI);
     XmlReader reader = null;
     try
     {
         Uri ruri = _xmlResolver.ResolveUri(_baseUri, uri.Substring(x_schema.Length));
         Stream stm = (Stream)_xmlResolver.GetEntity(ruri, null, null);
         reader = new XmlTextReader(ruri.ToString(), stm, _NameTable);
         schemaInfo = new SchemaInfo();
         Parser parser = new Parser(SchemaType.XDR, _NameTable, _SchemaNames, _validationEventHandler);
         parser.XmlResolver = _xmlResolver;
         parser.Parse(reader, uri);
         schemaInfo = parser.XdrSchema;
     }
     catch (XmlException e)
     {
         SendValidationEvent(SR.Sch_CannotLoadSchema, new string[] { uri, e.Message }, XmlSeverityType.Warning);
         schemaInfo = null;
     }
     finally
     {
         if (reader != null)
         {
             reader.Close();
         }
     }
     if (schemaInfo != null && schemaInfo.ErrorCount == 0)
     {
         _SchemaInfo.Add(schemaInfo, _validationEventHandler);
         return true;
     }
     return false;
 }
示例#52
0
        public static Version GetLastVersion(out string url)
        {
            Version newVersion = null;

            url = "";

            XmlTextReader reader = null;

            try {
                try {
                    #if NET35 || NET40
                    ServicePointManager.SecurityProtocol = (SecurityProtocolType)(ServicePointManager.SecurityProtocol | (SecurityProtocolType)Tls11 | (SecurityProtocolType)Tls12);
                    #else
                    ServicePointManager.SecurityProtocol = (SecurityProtocolType)(ServicePointManager.SecurityProtocol | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12);
                    #endif
                } catch (Exception ex) {
                    // crash on WinXP, TLS 1.2 not supported
                    Logger.WriteError("UpdateMan.GetLastVersion.SP()", ex);
                }

                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(UPDATE_URL);
                webRequest.ContentType = "text/xml; encoding='utf-8'";
                webRequest.KeepAlive   = false;
                webRequest.Method      = "GET";

                using (WebResponse webResponse = webRequest.GetResponse()) {
                    using (Stream stream = webResponse.GetResponseStream()) {
                        reader = new XmlTextReader(stream);
                        reader.MoveToContent();

                        string nodeName = "";
                        if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "gedkeeper"))
                        {
                            while (reader.Read())
                            {
                                if (reader.NodeType == XmlNodeType.Element)
                                {
                                    nodeName = reader.Name;
                                }
                                else
                                {
                                    if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue))
                                    {
                                        switch (nodeName)
                                        {
                                        case "version":
                                            newVersion = new Version(reader.Value);
                                            break;

                                        case "url":
                                            url = reader.Value;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                Logger.WriteError("UpdateMan.GetLastVersion()", ex);
            } finally {
                if (reader != null)
                {
                    reader.Close();
                }
            }

            return(newVersion);
        }
示例#53
0
        /**/
        /// <summary>   
        /// 读取Xml文件信息,并转换成DataSet对象    
        /// </summary>    
        /// <remarks>    
        /// DataSet ds = new DataSet();    
        /// ds = CXmlFileToDataSet("/XML/upload.xml");    
        /// </remarks>    
        /// <param name="xmlFilePath">Xml文件地址</param>    
        /// <returns>DataSet对象</returns>    
        public static DataSet CXmlFileToDataSet(string xmlFilePath)
        {
            if (!string.IsNullOrEmpty(xmlFilePath))
            {
                string path = HttpContext.Current.Server.MapPath(xmlFilePath);
                StringReader StrStream = null;
                XmlTextReader Xmlrdr = null;
                try
                {
                    XmlDocument xmldoc = new XmlDocument();
                    //根据地址加载Xml文件
                    xmldoc.Load(path);
                    DataSet ds = new DataSet();
                    //读取文件中的字符流
                    StrStream = new StringReader(xmldoc.InnerXml);
                    //获取StrStream中的数据
                    Xmlrdr = new XmlTextReader(StrStream);
                    //ds获取Xmlrdr中的数据
                    ds.ReadXml(Xmlrdr);
                    return ds;
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    //释放资源
                    if (Xmlrdr != null)
                    {
                        Xmlrdr.Close();
                        StrStream.Close();
                        StrStream.Dispose();
                    }
                }
            }
            else
            {
                return null;
            }
        }

        /**/
        /// <summary>   
        /// 将Xml内容字符串转换成DataSet对象    
        /// </summary>    
        /// <param name="xmlStr">Xml内容字符串</param>    
        /// <returns>DataSet对象</returns>    
        public static DataSet CXmlToDataSet(string xmlStr)
        {
            if (!string.IsNullOrEmpty(xmlStr))
            {
                StringReader StrStream = null;
                XmlTextReader Xmlrdr = null;
                try
                {
                    DataSet ds = new DataSet();
                    //读取字符串中的信息
                    StrStream = new StringReader(xmlStr);
                    //获取StrStream中的数据
                    Xmlrdr = new XmlTextReader(StrStream);
                    //ds获取Xmlrdr中的数据
                    ds.ReadXml(Xmlrdr);
                    return ds;
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    //释放资源
                    if (Xmlrdr != null)
                    {
                        Xmlrdr.Close();
                        StrStream.Close();
                        StrStream.Dispose();
                    }
                }
            }
            else
            {
                return null;
            }
        }
示例#54
0
        private void checkForUpdatesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string        downloadFullUrl = "";
            var           filenames       = new List <string>();
            Version       newVersion      = null;
            string        xmlUrl          = "http://jhunexjun.hostei.com/check-up/updates.xml";
            XmlTextReader reader          = null;

            try
            {
                reader = new XmlTextReader(xmlUrl);
                reader.MoveToContent();
                string elementName = ""; // the tag
                if ((reader.NodeType == XmlNodeType.Element) && reader.Name == "check-up")
                {
                    while (reader.Read())
                    {
                        if (reader.NodeType == XmlNodeType.Element)
                        {
                            elementName = reader.Name;
                        }
                        else
                        {
                            if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue))
                            {
                                switch (elementName)
                                {
                                case "version":
                                    newVersion = new Version(reader.Value);
                                    break;

                                case "downloadUrl":
                                    downloadFullUrl = reader.Value;
                                    break;

                                case "filename":
                                    filenames.Add(reader.Value);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }

            Version applicationVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

            if (applicationVersion.CompareTo(newVersion) < 0)
            {
                DialogResult dr = MessageBox.Show(this, "Version " + newVersion.ToString() + " of Check-up is now available. Do you want to download it now?", "New version", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dr == DialogResult.Yes)
                {
                    Uri baseUri = new Uri(downloadFullUrl);
                    if (baseUri.Scheme != Uri.UriSchemeFtp)
                    {
                        MessageBox.Show(this, "Uri is not a valid format.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
                    folderBrowserDialog1.ShowDialog();

                    if (folderBrowserDialog1.SelectedPath != "")
                    {
                        Uri fullUri = null; Uri relativeUri = null;
                        int i = filenames.Count, c = 0;

                        foreach (string filename in filenames)
                        {
                            relativeUri = new Uri(filename, UriKind.Relative);
                            fullUri     = new Uri(baseUri, relativeUri);
                            ftp ftpDownload = new ftp("a2278315", "Systems33");

                            if (ftpDownload.download(fullUri.ToString(), folderBrowserDialog1.SelectedPath + @"\" + relativeUri.ToString()))
                            {
                                // let's not use this for now
                                //unInstallSoftware();

                                c++;
                            }
                        }

                        if (c == 0)
                        {
                            MessageBox.Show(this, "Nothing has been downloaded. Try downloading again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else if (c > 0 && c == i)
                        {
                            MessageBox.Show(this, "All updates has been successfully downloaded.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else if (c > 0 && c < i)
                        {
                            MessageBox.Show(this, "One or more updates were not successully downloaded. Please download all.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                    }
                    else
                    {
                        MessageBox.Show(this, "No location has been selected. Downloading unsuccessful. Re-do the process if you want to download it.", "Download Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
            }
            else
            {
                MessageBox.Show(this, "This software is up-to-date.", "Message.", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
示例#55
0
        private void ReadReportsInfo()
        {
            #region Load
            string fileName = StiLocalization.CultureName;

            switch (fileName)
            {
            case "ua":
            case "be":
            case "ru":
                fileName = "ReportsRu.xml";
                break;

            default:
                fileName = "ReportsEn.xml";
                break;
            }

            StreamReader  sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Demo." + fileName));
            XmlTextReader tr = new XmlTextReader(sr);
            #endregion

            TreeNode categoryNode = null;

            bool is64Bit = IntPtr.Size == 8;

            tr.Read();
            while (!tr.EOF)
            {
                if (tr.IsStartElement())
                {
                    bool isNew = tr.GetAttribute("new") == "True";

                    #region Category
                    if (tr.Name == "Category")
                    {
                        bool x86Only = tr.GetAttribute("x86Only") == "True";
                        if (!(x86Only && is64Bit))
                        {
                            categoryNode     = new TreeNode(tr.GetAttribute("name"), 0, 0);
                            categoryNode.Tag = tr.GetAttribute("name");
                            tvReports.Nodes.Add(categoryNode);
                        }
                    }
                    #endregion

                    #region Report
                    else if (tr.Name == "Report")
                    {
                        bool x86Only = tr.GetAttribute("x86Only") == "True";
                        if (!(x86Only && is64Bit))
                        {
                            TreeNode reportNode = new TreeNode(tr.GetAttribute("name"), 1, 1);
                            reportNode.Tag = tr.GetAttribute("file");

                            if (tr.NodeType == XmlNodeType.Element)
                            {
                                reportInfo rptInfo = reportsHelper[reportNode.Tag] as reportInfo;
                                if (rptInfo == null)
                                {
                                    rptInfo = new reportInfo();
                                    reportsHelper[reportNode.Tag] = rptInfo;
                                }

                                tr.Read();
                                int depth = tr.Depth;
                                tr.Read();
                                while (tr.Depth >= depth && tr.NodeType != XmlNodeType.EndElement)
                                {
                                    switch (tr.Name)
                                    {
                                    case "desc":
                                        rptInfo.description = tr.ReadElementContentAsString();
                                        break;

                                    case "video":
                                        videoInfo video = new videoInfo();

                                        video.name        = tr.GetAttribute("name");
                                        video.description = tr.GetAttribute("desc");
                                        video.hyperlink   = tr.ReadElementContentAsString();
                                        rptInfo.videos.Add(video);
                                        break;

                                    case "sample":
                                        sampleInfo csSample = new sampleInfo();

                                        csSample.name        = tr.GetAttribute("name");
                                        csSample.description = tr.GetAttribute("desc");
                                        csSample.isVB        = tr.GetAttribute("vb") == "True";
                                        csSample.path        = tr.ReadElementContentAsString();
                                        rptInfo.samples.Add(csSample);
                                        break;
                                    }

                                    tr.Read();
                                }

                                tr.Read();
                            }
                            categoryNode.Nodes.Add(reportNode);
                        }
                    }
                    #endregion

                    #region Localization
                    else if (tr.Name == "Localization")
                    {
                        tr.Read();
                        int depth = tr.Depth;
                        tr.Read();
                        while (tr.Depth >= depth && tr.NodeType != System.Xml.XmlNodeType.EndElement)
                        {
                            string key     = tr.Name;
                            string content = tr.ReadElementContentAsString();
                            demoLocalization.Add(key, content);

                            tr.Read();
                        }
                    }
                    #endregion
                }
                tr.Read();
            }

            tr.Close();
            sr.Close();
            tvReports.Nodes[0].Expand();
        }
示例#56
0
        public bool importLoader(string s)
        {
            XmlTextReader textReader = new XmlTextReader(s);
            string        temp;

            try
            {
                while (textReader.Read())
                {
                    if (textReader.IsStartElement())
                    {
                        if (textReader.Name == "targetDirectory")
                        {
                            temp = textReader.ReadString();
                            targetDirectory.Text = temp;
                            loadHelper(temp);
                        }
                        else if (textReader.Name == "profileSelection")
                        {
                            temp = textReader.ReadString();
                            if (temp == "all")
                            {
                                allProfiles.Checked = true;
                            }
                            else
                            {
                                selectProfiles.Checked = true;
                                profileListBox.ClearSelected();
                            }
                        }
                        else if (textReader.Name == "profile")
                        {
                            temp = textReader.ReadString();
                            int i     = temp.LastIndexOf("\\");
                            int index = profileListBox.FindString(temp.Remove(0, i + 1));
                            if (index >= 0)
                            {
                                profileListBox.SetSelected(index, true);
                            }
                        }
                        else if (textReader.Name == "folderSelection")
                        {
                            temp = textReader.ReadString();
                            if (temp == "temp")
                            {
                                tempFolder.Checked = true;
                            }
                            else if (temp == "all")
                            {
                                allFolders.Checked = true;
                            }
                            else
                            {
                                selectFolders.Checked = true;
                                folderList.Text       = temp;
                            }
                        }
                        else if (textReader.Name == "includeSubfolders")
                        {
                            temp = textReader.ReadString();
                            if (temp == "true")
                            {
                                includeSub.Checked = true;
                            }
                            else
                            {
                                includeSub.Checked = false;
                            }
                        }
                        else if (textReader.Name == "fileTypes")
                        {
                            temp = textReader.ReadString();
                            if (temp == "all")
                            {
                                allTypes.Checked = true;
                            }
                            else
                            {
                                selectTypes.Checked = true;
                                extensionList.Text  = temp;
                            }
                        }
                        else if (textReader.Name == "fileSelection")
                        {
                            temp = textReader.ReadString();
                            if (temp == "all")
                            {
                                allFiles.Checked = true;
                            }
                        }
                        else if (textReader.Name == "fromDate")
                        {
                            dateRange.Checked = true;
                            fromDate.Value    = Convert.ToDateTime(textReader.ReadString());
                        }
                        else if (textReader.Name == "toDate")
                        {
                            dateRange.Checked = true;
                            toDate.Value      = Convert.ToDateTime(textReader.ReadString());
                        }
                        else if (textReader.Name == "dateCut")
                        {
                            dateCut.Checked = true;
                            daysOld.Text    = textReader.ReadString();
                        }
                        else if (textReader.Name == "backup")
                        {
                            temp = textReader.ReadString();
                            if (temp == "false")
                            {
                                saveBackup.Checked = false;
                            }
                        }
                        else if (textReader.Name == "backupDirectory")
                        {
                            saveBackup.Checked   = true;
                            backupDirectory.Text = textReader.ReadString();
                        }
                        else if (textReader.Name == "simulation")
                        {
                            temp = textReader.ReadString();
                            if (temp == "true")
                            {
                                simulation.Checked = true;
                            }
                            else
                            {
                                simulation.Checked = false;
                            }
                        }
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
            finally
            {
                textReader.Close();
            }
        }
    /// <summary>
    /// Gets the created worlds.
    /// </summary>
    /// <returns>The created worlds.</returns>
    public static List<WorldSpecs> GetCreatedWorlds()
    {
        if(File.Exists(directory + "CreatedWorlds.xml"))
        {
            List<WorldSpecs> existingSpecs = new List<WorldSpecs> ();
            XmlTextReader reader = new XmlTextReader(directory + "CreatedWorlds.xml");

            while(reader.Read())
            {
                if(reader.IsStartElement() && reader.NodeType == XmlNodeType.Element)
                {
                    switch(reader.Name)
                    {
                        case "WorldSpec":
                            if(reader.AttributeCount >= 10)
                            {
                                WorldSpecs tempSpec = new WorldSpecs();
                                tempSpec.spaceName = reader.GetAttribute(0);
                                tempSpec.spaceArea = int.Parse(reader.GetAttribute(1));
                                tempSpec.mapLength = int.Parse(reader.GetAttribute(2));
                                tempSpec.cellLength = float.Parse(reader.GetAttribute(3));
                                tempSpec.start = new Vector2(float.Parse(reader.GetAttribute(4)),float.Parse(reader.GetAttribute(5)));
                                tempSpec.degreeJumpStep = float.Parse(reader.GetAttribute(6));
                                tempSpec.subdivisions = int.Parse(reader.GetAttribute(7));
                                tempSpec.totalNumberOfCells = int.Parse(reader.GetAttribute(8));
                                tempSpec.seed = int.Parse(reader.GetAttribute(9));
                                tempSpec.planetPositions = new Vector2[(reader.AttributeCount - 10) / 2];
                                if(reader.AttributeCount > 11)
                                {
                                    float maxPosition = (reader.AttributeCount - 10)/2.0f;
                                    int maxP = Mathf.CeilToInt(maxPosition);
                                    for(int i = 0, j = 0; j < maxP; j++)
                                    {
                                        tempSpec.planetPositions[j].Set(float.Parse(reader.GetAttribute(i+10)), float.Parse(reader.GetAttribute(i+11)));
                                     	i+= 2;
                                    }
                                }
                                existingSpecs.Add(tempSpec);
                            }
                            else
                            {
                                Debug.Log("Data is missing from 1 of the worlds. Not Saving it anymore");
                            }
                            break;
                        case "Root":
                            break;
                        default:
                            Debug.Log(reader.Name + " : possible invalid data in save file ignoring, please review file");
                            break;
                    }
                }
            }

            reader.Close();
            return existingSpecs;
        }
        else
        {
            return new List<WorldSpecs>(1);
        }
    }
示例#58
0
        /// <summary>
        /// Deserializes an object from file and returns a reference.
        /// </summary>
        /// <param name="fileName">name of the file to serialize to</param>
        /// <param name="objectType">The Type of the object. Use typeof(yourobject class)</param>
        /// <param name="binarySerialization">determines whether we use Xml or Binary serialization</param>
        /// <param name="throwExceptions">determines whether failure will throw rather than return null on failure</param>
        /// <returns>Instance of the deserialized object or null. Must be cast to your object type</returns>
        public static object DeSerializeObject(string fileName, Type objectType, bool binarySerialization, bool throwExceptions)
        {
            object instance = null;

            if (!binarySerialization)
            {
                XmlReader     reader     = null;
                XmlSerializer serializer = null;
                FileStream    fs         = null;
                try
                {
                    // Create an instance of the XmlSerializer specifying type and namespace.
                    serializer = new XmlSerializer(objectType);

                    // A FileStream is needed to read the XML document.
                    fs     = new FileStream(fileName, FileMode.Open);
                    reader = new XmlTextReader(fs);

                    instance = serializer.Deserialize(reader);
                }
                catch (Exception ex)
                {
                    if (throwExceptions)
                    {
                        throw;
                    }

                    string message = ex.Message;
                    return(null);
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }

                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
            else
            {
                BinaryFormatter serializer = null;
                FileStream      fs         = null;

                try
                {
                    serializer = new BinaryFormatter();
                    fs         = new FileStream(fileName, FileMode.Open);
                    instance   = serializer.Deserialize(fs);
                }
                catch
                {
                    return(null);
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                }
            }

            return(instance);
        }
 private void WriteDataToResourceFile(String fileFormat, ResourceWriter resWriter, CultureInfo culture){
 ArrayList xmlTable;
 ArrayList xmlList;
 Int32 ielementCount;
 String elementName;
 StringBuilder resourceHolder;
 String resourceName;
 XmlTextReader reader;
 xmlTable = new ArrayList();
 xmlList = new ArrayList();
 reader = new XmlTextReader(xmlSchemaFile + "_" + fileFormat + ".xml");
 ielementCount=0;
 while (reader.Read())
   {
   switch (reader.NodeType)
     {
     case XmlNodeType.Element:
       if (reader.HasAttributes)
	 {
	 if(++ielementCount>2){
	 xmlTable.Add(String.Empty);
	 xmlList.Add(reader[0]);
	 }
	 }
       break;
     }
   }
 reader.Close();
 reader = new XmlTextReader(xmlDataFile  + "_" + fileFormat + "_" + culture.ToString() + ".xml");
 elementName = String.Empty;
 while (reader.Read())
   {
   switch (reader.NodeType)
     {
     case XmlNodeType.Element:
       elementName = reader.Name;
       break;
     case XmlNodeType.Text:
       if(xmlList.Contains(elementName)){
       xmlTable[xmlList.IndexOf(elementName)] = (String)xmlTable[xmlList.IndexOf(elementName)] + reader.Value + separator;
       }
       break;
     }
   }
 reader.Close();
 resourceHolder = new StringBuilder();
 foreach(String str111 in xmlList){
 resourceHolder.Append((String)xmlTable[xmlList.IndexOf(str111)] + EOL);
 }
 resourceName = baseFileName + fileFormat + culture.ToString();
 resWriter.AddResource(resourceName, resourceHolder.ToString());
 }
示例#60
0
文件: Form1.cs 项目: NolascoT/CRUD
        private void button2_Click(object sender, EventArgs e)
        {
            string UMLClassDiagram   = "UMLClassDiagram";
            string superitem         = "superitem";
            string UMLAssociation    = "UMLAssociation";
            string point             = "point";
            string UMLGeneralization = "UMLGeneralization";
            string valueAst          = "value=\"*\"";
            string valueUno          = "value=\"1\"";
            string valueNulo         = "value=\"\"";
            char   quitalo           = '+';
            char   quitalo2          = ':';
            char   quitalo3          = '_';
            char   quitalo4          = '#';

            string line;

            string       NewXml     = "";
            StreamReader seCargoXml = new StreamReader(textBox1.Text);

            while ((line = seCargoXml.ReadLine()) != null)
            {
                if (line.Contains(UMLClassDiagram) ||
                    line.Contains(superitem) || line.Contains(UMLAssociation) ||
                    line.Contains(point) || line.Contains(UMLGeneralization) ||
                    line.Contains(valueAst) || line.Contains(valueUno) ||
                    line.Contains(valueNulo))
                {
                }
                else
                {
                    if (line.Contains(quitalo))
                    {
                        line = line.Replace("+", "");
                    }
                    if (line.Contains(quitalo2))
                    {
                        line = line.Replace(":", " ");
                    }
                    if (line.Contains(quitalo3))
                    {
                        line = line.Replace("_", "");
                    }
                    if (line.Contains(quitalo4))
                    {
                        line = line.Replace("#", "");
                    }
                    NewXml           += line;
                    richTextBox1.Text = NewXml;
                }
            }
            seCargoXml.Close();
            Console.WriteLine(NewXml);

            XmlTextReader reader = new XmlTextReader(new StringReader(NewXml));
            StringWriter  writer = new StringWriter();

            while (reader.Read())
            {
                //cadena que almacenará la indentación
                string indentado = new string('\t', reader.Depth);
                //evaluando el tipo de nodo
                switch (reader.NodeType)
                {
                //si tipo de nodo es: <?xml version='1.0' encoding='ISO-8859-1'?>
                case XmlNodeType.XmlDeclaration:
                    //usamos Value para imprimir "xml version='1.0' encoding='ISO-8859-1'"
                    writer.WriteLine("<?{0}?>", reader.Value);
                    break;

                //if el tipo de nodo es un comentario
                case XmlNodeType.Comment:
                    writer.WriteLine("{0}<!--{1}-->", indentado, reader.Value);
                    break;

                //si tipo de nodo es elemento
                case XmlNodeType.Element:
                {
                    //y si tiene atributos
                    if (reader.HasAttributes)
                    {
                        //entonces creamos una cadena "atributos" que guardará
                        //los atributos de este nodo.
                        if (reader.LocalName == "UMLClass")
                        {
                            writer.WriteLine("{0}<UMLClass>", indentado);
                        }
                        string atributos = null;
                        string Id        = null;
                        for (int i = 0; i < reader.AttributeCount; i++)
                        {
                            //nos movemos para realizar la lectura del atrbiuto de acuerdo al índice.
                            reader.MoveToAttribute(i);
                            //una vez que estamos ubicados en la posición correcta,
                            //leemos el nombre del atributo, como también el valor.
                            if (i == 1 && reader.Name == "value")
                            {
                                Id += reader.Value;
                                writer.WriteLine("{0}<Id>{1}</Id>", indentado, Id);
                            }
                            if (i == 0 && reader.Name != "id" && reader.LocalName != "UMLClass")
                            {
                                atributos += reader.Value;
                                writer.WriteLine("{0}<atributo>{1}</atributo>", indentado, atributos);
                            }
                        }
                        //despues de haber leido los atributos del elemento...
                        //moveremos el puntero al elemento.
                        reader.MoveToElement();
                    }
                    else
                    {
                        //si la profundidad del nodo es diferente a 2
                        if (reader.Depth != 2)
                        {
                            writer.WriteLine("{0}<{1}>", indentado, reader.LocalName);
                        }
                        else
                        {
                            writer.Write("{0}<{1}>", indentado, reader.LocalName);
                        }
                    }
                }
                break;

                //if el tipo de nodo es contenido.
                case XmlNodeType.Text:
                    //imprimimos el contenido.
                    writer.Write(reader.Value);
                    break;

                //si el tipo de nodo es un elemento final o de cierre.
                case XmlNodeType.EndElement:
                    //y además, averiguamos si es el que Depth es 2 entonces
                    //no le agregamos la indentación, imprimiendo de esta manera:
                    //<title>XML Programming</title> en vez de <title>XML Programming        </title>
                    if (reader.Depth == 2)
                    {
                        writer.WriteLine("</{0}>", reader.LocalName);
                    }
                    else
                    {
                        //con indentación tabPrefix
                        writer.WriteLine("{0}</{1}>", indentado, reader.LocalName);
                    }
                    break;
                }
            }
            //cerramos el reader
            reader.Close();
            //mostrar los resultados.
            string text = writer.ToString();

            Console.Write(text);
            richTextBox2.Text = writer.ToString();
        }