Наследование: XmlReader, IXmlLineInfo
Пример #1
1
        public AvatarAnimations()
        {
            using (XmlTextReader reader = new XmlTextReader("data/avataranimations.xml"))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(reader);
                foreach (XmlNode nod in doc.DocumentElement.ChildNodes)
                {
                    if (nod.Attributes["name"] != null)
                    {
                        string name = nod.Attributes["name"].Value;
                        UUID id = (UUID) nod.InnerText;
                        string animState = nod.Attributes["state"].Value;

                        try
                        {
                            AnimsUUID.Add(name, id);
                            if (animState != "" && !AnimStateNames.ContainsKey(id))
                                AnimStateNames.Add(id, animState);
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }
        public static IncomingTransportMessage Deserialize(string messageId, Stream inputStream)
        {
            var headers = new Dictionary<string, string>();
            var serializedMessageData = "";
            using (var reader = new XmlTextReader(inputStream))
            {
                reader.WhitespaceHandling = WhitespaceHandling.None;
                reader.Read(); // read <root>
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        var elementName = reader.Name;
                        reader.Read(); // read the child;
                        while (reader.NodeType == XmlNodeType.Element)
                        {
                            // likely an empty header element node
                            headers.Add(elementName, reader.Value);

                            elementName = reader.Name;
                            reader.Read(); // read the child;
                        }
                        if (string.Equals(elementName, "body", StringComparison.InvariantCultureIgnoreCase) && reader.NodeType == XmlNodeType.CDATA)
                        {
                            serializedMessageData = reader.Value;
                        }
                        else if (reader.NodeType == XmlNodeType.Text)
                        {
                            headers.Add(elementName, reader.Value);
                        }
                    }
                }
            }
            return new IncomingTransportMessage(messageId, headers, serializedMessageData);
        }
Пример #3
0
        private static StringBuilder Transform(string gcmlPath)
        {
            if(!File.Exists(gcmlPath))
            {
                throw new GCMLFileNotFoundException("The GCML File" + gcmlPath + " does not exist.");
            }

            if(!File.Exists(xsltFilePath))
            {
                throw new XSLTFileNotFoundException("The XSLT File" + xsltFilePath + " does not exist.");
            }

            StringBuilder sb = new StringBuilder();
            XmlTextReader xmlSource = new XmlTextReader(gcmlPath);
            XPathDocument xpathDoc = new XPathDocument(xmlSource);
            XslCompiledTransform xsltDoc = new XslCompiledTransform();

            xsltDoc.Load(xsltFilePath);

            StringWriter sw = new StringWriter(sb);
            try
            {
                xsltDoc.Transform(xpathDoc, null, sw);
            }
            catch (XsltException except)
            {
                Console.WriteLine(except.Message);
                throw except;
            }

            return sb;
        }
        public override int Run(string[] args)
        {
            string schemaFileName = args[0];
            string outschemaFileName = args[1];

            XmlTextReader xr = new XmlTextReader(schemaFileName);
            SchemaInfo schemaInfo = SchemaManager.ReadAndValidateSchema(xr, Path.GetDirectoryName(schemaFileName));
            schemaInfo.Includes.Clear();
            schemaInfo.Classes.Sort(CompareNames);
            schemaInfo.Relations.Sort(CompareNames);

            XmlSerializer ser = new XmlSerializer(typeof(SchemaInfo));
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", SchemaInfo.XmlNamespace);

            using (FileStream fs = File.Create(outschemaFileName))
            {
                try
                {
                    ser.Serialize(fs, schemaInfo, ns);
                }
                finally
                {
                    fs.Flush();
                    fs.Close();
                }
            }

            return 0;
        }
        internal void ReadXml(XmlTextReader reader)
        {
            while (reader.Read())
            {
                // End of credit_card element, get out of here
                if (reader.Name == "credit_card" && reader.NodeType == XmlNodeType.EndElement)
                    break;

                if (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.Name)
                    {
                        case "year":
                            this.ExpirationYear = reader.ReadElementContentAsInt();
                            break;

                        case "month":
                            this.ExpirationMonth = reader.ReadElementContentAsInt();
                            break;

                        case "last_four":
                            this.LastFour = reader.ReadElementContentAsString();
                            break;

                        case "type":
                            this.CreditCardType = reader.ReadElementContentAsString();
                            break;
                    }
                }
            }
        }
Пример #6
0
        private void FromXml(String xmlStream)
        {
            try
            {
                StringReader stringReader = new StringReader(xmlStream);
                XmlTextReader reader = new XmlTextReader(stringReader);
                while (reader.EOF == false)
                {
                    reader.ReadStartElement("ValidationContext");
                    String generateSummaryResults = reader.ReadElementString("GenerateSummaryResults");
                    if (generateSummaryResults == "true")
                    {
                        _generateSummaryResults = true;
                    }
                    String generateDetailedResults = reader.ReadElementString("GenerateDetailedResults");
                    if (generateDetailedResults == "true")
                    {
                        _generateDetailedResults = true;
                    }
                    // ...
                    // EVS Specific Context properties
                    // ...
                    reader.ReadElementString("EvsSpecificContext");

                    reader.ReadEndElement();
                }
                reader.Close();
            }
            catch (Exception e)
            {
                String message = String.Format("Failed to FromXml() DVTK DICOM EVS Validation Context XML stream: \"{0}\". Error: \"{1}\"", xmlStream, e.Message);
                throw new Exception(message, e);
            }
        }
        protected override void ProcessRecord()
        {
            const BindingFlags commonBindings = BindingFlags.NonPublic | BindingFlags.Instance;
            const BindingFlags methodBindings = BindingFlags.InvokeMethod | commonBindings;
            var type = typeof(PSObject).Assembly.GetType("System.Management.Automation.Deserializer");
            var ctor = type.GetConstructor(commonBindings, null, new[] { typeof(XmlReader) }, null);

            using (var sr = new StringReader(InputObject))
            {
                using (var xr = new XmlTextReader(sr))
                {
                    var deserializer = ctor.Invoke(new object[] { xr });
                    while (!(bool)type.InvokeMember("Done", methodBindings, null, deserializer, new object[] { }))
                    {
                        try
                        {
                            WriteObject(type.InvokeMember("Deserialize", methodBindings, null, deserializer, new object[] { }));
                        }
                        catch (Exception ex)
                        {
                            WriteWarning("Could not deserialize string. Exception: " + ex.Message);
                        }
                    }
                }
            }
        }
 public CategoriesInfoRepository()
 {
     XmlReader reader = new XmlTextReader(path);
     List<CategoryInfo> infoFromXml = (List<CategoryInfo>)writers.Deserialize(reader);
     reader.Close();
     this.categoriesInfolList = infoFromXml;
 }
		public CAGCategory( CAGCategory parent, XmlTextReader xml )
		{
			m_Parent = parent;

			if ( xml.MoveToAttribute( "title" ) )
				m_Title = xml.Value;
			else
				m_Title = "empty";

			if ( m_Title == "Docked" )
				m_Title = "Docked 2";

			if ( xml.IsEmptyElement )
			{
				m_Nodes = new CAGNode[0];
			}
			else
			{
				ArrayList nodes = new ArrayList();

				/*while ( xml.Read() && xml.NodeType != XmlNodeType.EndElement )
				{
					if ( xml.NodeType == XmlNodeType.Element && xml.Name == "object" )
						nodes.Add( new CAGObject( this, xml ) );
					else if ( xml.NodeType == XmlNodeType.Element && xml.Name == "category" )
						nodes.Add( new CAGCategory( this, xml ) );
					else
						xml.Skip();
				}*/

				m_Nodes = (CAGNode[])nodes.ToArray( typeof( CAGNode ) );
			}
		}
Пример #10
0
        public List<ProgramElement> Parse(string filename)
        {
            var programElements = new List<ProgramElement>();

            XmlTextReader reader = new XmlTextReader(filename);

            while (reader.Read())
            {
                string text = String.Empty;

                if (reader.NodeType == XmlNodeType.Text)
                {
                    text = reader.Value;
                }
                else if (reader.NodeType == XmlNodeType.Element)
                {
                    while (reader.MoveToNextAttribute())
                    {
                        text += reader.Value + " ";
                    }
                }

                if (!String.IsNullOrWhiteSpace(text))
                {
                    var cleanedText = text.TrimStart(' ', '\n', '\r', '\t');
                    cleanedText = cleanedText.TrimEnd(' ', '\n', '\r', '\t');
                    var linenum = reader.LineNumber;
                    var snippet = SrcMLParsingUtils.RetrieveSource(cleanedText);
                    var pe = new TextFileElement(filename, snippet, cleanedText);
                    programElements.Add(pe);
                }
            }

            return programElements;
        }
        public void OnStartUp()
        {
            SetRootPathProject();

            XmlTextReader configReader = new XmlTextReader(new MemoryStream(NHibernate.Test.Properties.Resources.Configuration));
            DirectoryInfo dir = new DirectoryInfo(this.rootPathProject + ".Hbm");
            Console.WriteLine(dir);

            builder = new NhConfigurationBuilder(configReader, dir);

            builder.SetProperty("connection.connection_string", GetConnectionString());

            try
            {
                builder.BuildSessionFactory();
                sessionFactory = builder.SessionFactory;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
            
            sessionProvider = new SessionManager(sessionFactory);
            currentPagedDAO = new EnterprisePagedDAO(sessionProvider);
            currentRootPagedDAO = new EnterpriseRootDAO<object>(sessionProvider);
            currentSession = sessionFactory.OpenSession();
        }
Пример #12
0
 private static void LoadChannels()
 {
     XmlReader reader = new XmlTextReader("channel.xml");
     while (reader.Read())
     {
         switch (reader.Name)
         {
             case "CHANNEL":
                 MMatchChannel channel = new MMatchChannel();
                 channel.szName = reader.GetAttribute("name");
                 if (!Int32.TryParse(reader.GetAttribute("levelmin"), out channel.nMinLevel))
                     channel.nMinLevel = 0;
                 channel.nMaxUsers = Int32.Parse(reader.GetAttribute("maxplayers"));
                 channel.uidChannel = Convert.ToUInt64(mChannels.Count);
                 channel.nChannelType = MMatchChannelType.General;
                 switch (reader.GetAttribute("rule"))
                 {
                     case "elite":
                         channel.nChannelRule = MMatchChannelRule.Elite;
                         break;
                 }
                 mChannels.Add(channel);
                 break;
         }
     }
 }
Пример #13
0
		public TemplateInfo[] ReadTemplates()
		{
			ArrayList result = new ArrayList();
			if(Directory.Exists(_templateFolder))
			{
				foreach(string dir in Directory.GetDirectories(_templateFolder))
				{
					string templateFile = Path.Combine(dir, "template.xml");
					if( File.Exists(templateFile ) )
					{
						XmlTextReader reader = new XmlTextReader(templateFile);
						try
						{
							reader.Read();
							reader.ReadStartElement("Template");
							reader.ReadStartElement("TemplateData");
							reader.ReadStartElement("Name");
							string name = reader.ReadString();
							DirectoryInfo directoryInfo = new DirectoryInfo(dir);
							TemplateInfo templateInfo = new TemplateInfo(name, directoryInfo.Name );
							result.Add(templateInfo);
						}
						finally
						{
							reader.Close();
						}
					}
				}
			}
			return (TemplateInfo[])result.ToArray(typeof(TemplateInfo));
		}
Пример #14
0
        private static void LoadItems()
        {
            XmlReader reader = new XmlTextReader("zitem.xml");
            while (reader.Read())
            {
                switch (reader.Name)
                {
                    case "ITEM":
                        Item item = new Item();
                        item.nItemID = Int32.Parse(reader.GetAttribute("id"));
                        item.nLevel = (byte)Int32.Parse(reader.GetAttribute("res_level"));
                        item.nWeight = Int32.Parse(reader.GetAttribute("weight"));
                        item.nMaxWT = reader.GetAttribute("maxwt") == null ? 0 : Int32.Parse(reader.GetAttribute("maxwt"));
                        item.nPrice = reader.GetAttribute("bt_price") == null ? 0 : Int32.Parse(reader.GetAttribute("bt_price"));
                        mItems.Add(item);
                        break;
                }
            }

            reader = new XmlTextReader("shop.xml");
            while (reader.Read())
            {
                switch (reader.Name)
                {
                    case "SELL":
                        mShop.Add(UInt32.Parse(reader.GetAttribute("itemid")));
                        break;
                }
            }
        }
Пример #15
0
 private void advanceToElement(ref XmlTextReader reader, string element)
 {
     while (!reader.Name.EndsWith(element))
     {
         reader.Read();
     }
 }
Пример #16
0
        /// <summary>
        /// Constructs the Arcs using Xml
        /// </summary>
        /// <param name="vsXml">Xml data</param>
        public Arcs(string vsXml)
        {
            XmlTextReader reader = new XmlTextReader(new StringReader(vsXml));
            reader.Read();

            ArcType = (EnumArcType)Enum.Parse(typeof(EnumArcType), reader.GetAttribute("arctype"));

            moArcList = new List<Arc>();

            while (reader.Read())
            {
                switch (reader.Name)
                {
                    case "Arcs" :
                        if (reader.NodeType != XmlNodeType.EndElement)
                        {
                            if (moInnerArcs == null)
                            {
                                moInnerArcs = new List<Arcs>();
                            }
                            moInnerArcs.Add(new Arcs(reader.ReadOuterXml()));
                        }
                        break;
                    case "Arc" :
                        moArcList.Add(new Arc(reader.ReadOuterXml()));
                        break;
                }
            }
        }
		List<SyntaxMode> ScanDirectory(string directory)
		{
			string[] files = Directory.GetFiles(directory);
			List<SyntaxMode> modes = new List<SyntaxMode>();
			foreach (string file in files) {
				if (Path.GetExtension(file).Equals(".XSHD", StringComparison.OrdinalIgnoreCase)) {
					XmlTextReader reader = new XmlTextReader(file);
					while (reader.Read()) {
						if (reader.NodeType == XmlNodeType.Element) {
							switch (reader.Name) {
								case "SyntaxDefinition":
									string name       = reader.GetAttribute("name");
									string extensions = reader.GetAttribute("extensions");
									modes.Add(new SyntaxMode(Path.GetFileName(file),
									                         name,
									                         extensions));
									goto bailout;
								default:
									throw new HighlightingDefinitionInvalidException("Unknown root node in syntax highlighting file :" + reader.Name);
							}
						}
					}
				bailout:
					reader.Close();
					
				}
			}
			return modes;
		}
Пример #18
0
        private void FlashMovieFlashCall(object sender, _IShockwaveFlashEvents_FlashCallEvent e)
        {
            try
            {
                XmlTextReader reader = new XmlTextReader(new StringReader(e.request));
                reader.WhitespaceHandling = WhitespaceHandling.Significant;
                reader.MoveToContent();

                if (reader.Name == "invoke" && reader.GetAttribute("name") == "trace")
                {
                    reader.Read();
                    if (reader.Name == "arguments")
                    {
                        reader.Read();
                        if (reader.Name == "string")
                        {
                            reader.Read();
                            TraceManager.Add(reader.Value, 1);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorManager.ShowError(ex);
            }
        }
Пример #19
0
 public Parser(XmlTextReader reader)
 {
     this.reader = reader;
     this.reader.WhitespaceHandling = WhitespaceHandling.None;
        // 'None' only prevents whitespace  being returned as a node
        // Now assuming that there is no embedded whitespace that isn't significant.
 }
Пример #20
0
 /// <summary>
 /// Creates an instance of the given type from the specified Internet resource.
 /// </summary>
 /// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
 /// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param>
 /// <param name="xsltArgs">An <see cref="XsltArgumentList"/> containing the namespace-qualified arguments used as input to the transform.</param>
 /// <param name="type">The requested type.</param>
 /// <param name="xmlPath">A file path where the temporary XML before transformation will be saved. Mostly used for debugging purposes.</param>
 /// <returns>An newly created instance.</returns>
 public object CreateInstance(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, Type type,
                              string xmlPath)
 {
     StringWriter sw = new StringWriter();
     XmlTextWriter writer = new XmlTextWriter(sw);
     if (xsltUrl == null)
     {
         LoadHtmlAsXml(htmlUrl, writer);
     }
     else
     {
         if (xmlPath == null)
         {
             LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer);
         }
         else
         {
             LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer, xmlPath);
         }
     }
     writer.Flush();
     StringReader sr = new StringReader(sw.ToString());
     XmlTextReader reader = new XmlTextReader(sr);
     XmlSerializer serializer = new XmlSerializer(type);
     object o;
     try
     {
         o = serializer.Deserialize(reader);
     }
     catch (InvalidOperationException ex)
     {
         throw new Exception(ex + ", --- xml:" + sw);
     }
     return o;
 }
Пример #21
0
        protected void visualizeDo_Click(object sender, EventArgs e)
        {

            // get xslt file
            string xslt = "";
            if (xsltSelection.Value.Contains("<xsl:stylesheet"))
            {
                xslt = xsltSelection.Value;
            }
            else
            {
                System.IO.StreamReader xsltFile =
                System.IO.File.OpenText(
                    IOHelper.MapPath(SystemDirectories.Umbraco + "/xslt/templates/clean.xslt")
                );

                xslt = xsltFile.ReadToEnd();
                xsltFile.Close();

                // parse xslt
                xslt = xslt.Replace("<!-- start writing XSLT -->", xsltSelection.Value);

                // prepare support for XSLT extensions
                xslt = macro.AddXsltExtensionsToHeader(xslt);

            }

            Dictionary<string, object> parameters = new Dictionary<string, object>(1);
            parameters.Add("currentPage", library.GetXmlNodeById(contentPicker.Value));


            // apply the XSLT transformation
            string xsltResult = "";
            XmlTextReader xslReader = null;
            try
            {
                xslReader = new XmlTextReader(new StringReader(xslt));
                System.Xml.Xsl.XslCompiledTransform xsl = macro.CreateXsltTransform(xslReader, false);
                xsltResult = macro.GetXsltTransformResult(new XmlDocument(), xsl, parameters);
            }
            catch (Exception ee)
            {
                xsltResult = string.Format(
                    "<div class=\"error\"><h3>Error parsing the XSLT:</h3><p>{0}</p></div>",
                    ee.ToString());
            }
            finally
            {
                xslReader.Close();
            }
            visualizeContainer.Visible = true;

            // update output
            visualizeArea.Text = !String.IsNullOrEmpty(xsltResult) ? "<div id=\"result\">" + xsltResult + "</Div>" : "<div class=\"notice\"><p>The XSLT didn't generate any output</p></div>";


            // add cookie with current page
			// zb-00004 #29956 : refactor cookies names & handling
			cookie.SetValue(contentPicker.Value);
        }
        /// <summary> Reads metadata from an open stream and saves to the provided item/package </summary>
        /// <param name="Input_Stream"> Open stream to read metadata from </param>
        /// <param name="Return_Package"> Package into which to read the metadata </param>
        /// <param name="Options"> Dictionary of any options which this metadata reader/writer may utilize </param>
        /// <param name="Error_Message">[OUTPUT] Explanation of the error, if an error occurs during reading </param>
        /// <returns>TRUE if successful, otherwise FALSE </returns>
        public bool Read_Metadata(Stream Input_Stream, SobekCM_Item Return_Package, Dictionary<string, object> Options, out string Error_Message)
        {
            // Set default error outpt message
            Error_Message = String.Empty;

            // Create a XML reader and read the metadata
            XmlTextReader nodeReader = null;
            bool returnValue = true;
            try
            {
                // create the node reader
                nodeReader = new XmlTextReader(Input_Stream);
                MODS_METS_dmdSec_ReaderWriter.Read_MODS_Info(nodeReader, Return_Package.Bib_Info, Return_Package);
            }
            catch (Exception ee)
            {
                Error_Message = "Error reading MODS from stream: " + ee.Message;
                returnValue = false;
            }
            finally
            {
                if (nodeReader != null)
                    nodeReader.Close();
            }

            return returnValue;
        }
Пример #23
0
 public static List<PackageInfo> LoadUpdateList(string fileName)
 {
     XmlSerializer serializer = new XmlSerializer(typeof(List<PackageInfo>));
     XmlTextReader xmlTextReader = new XmlTextReader(fileName);
     _updateList = (List<PackageInfo>)serializer.Deserialize(xmlTextReader);
     return _updateList;
 }
Пример #24
0
        public void GetObject(string strResource, string strID, string strType)
        {
            string requestArguments = "?Resource=" + strResource + "&ID=" + strID + "&Type=" + strType;
            string searchService = RetsUrl + "/GetObject.svc/GetObject" + requestArguments;

            httpWebRequest = (HttpWebRequest)WebRequest.Create(searchService);
            httpWebRequest.CookieContainer = cookieJar; //GRAB THE COOKIE
            httpWebRequest.Credentials = requestCredentials; //PASS CREDENTIALS

            try
            {
                using (HttpWebResponse httpResponse = httpWebRequest.GetResponse() as HttpWebResponse)
                {

                    // READ THE RESPONSE STREAM USING XMLTEXTREADER
                    if (httpResponse.StatusCode == HttpStatusCode.OK)
                    {
                        Stream stream = httpResponse.GetResponseStream(); // READ THE RESPONSE STREAM USING STREAMREADER
                        StreamReader reader = new StreamReader(stream);
                        XmlTextReader reader2 = new XmlTextReader(stream);
                        XmlDocument doc = new XmlDocument();
                        doc.Load(reader);
                        doc.Save(HttpContext.Current.Server.MapPath(strResource + "Obj.xml"));
                        Console.WriteLine("Received photo -> resource:" + strResource + ", type: " + strType);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Пример #25
0
        private string ReadTokensFromXML()
        {
            string tokens = String.Empty;

            try
            {
                XmlTextReader tokensXmlReader = new XmlTextReader(String.Format(@"{0}\{1}",
                                                                  System.IO.Directory.GetCurrentDirectory(),
                                                                  xmlName));
                while (tokensXmlReader.Read())
                {
                    if (tokensXmlReader.NodeType == XmlNodeType.Element && tokensXmlReader.Name == "token")
                    {
                        tokens += String.Format("Token \"{0}\"\n \tLine: {1}\n \tPosition: {2}\n \tValue: {3}\n\n",
                                                tokensXmlReader.GetAttribute("type"),
                                                Convert.ToString(Convert.ToInt32(tokensXmlReader.GetAttribute("line")) + 1),
                                                tokensXmlReader.GetAttribute("position"),
                                                tokensXmlReader.GetAttribute("value"));
                    }
                }

                tokensXmlReader.Close();
                return tokens;
            }
            catch
            {
                return "";
            }
        }
Пример #26
0
        /// <summary>
        /// Load matrix from XML file
        /// </summary>
        /// <param name="fileName">file name</param>
        /// <returns>Loaded matrix</returns>
        public Matrix Load(string fileName)
        {
            XmlTextReader textReader = new XmlTextReader(fileName);
            Matrix matrix = new Matrix();
            string fromWord = null;
            string toWord;
            float statisticValue;

            while (textReader.Read())
            {
                if (textReader.NodeType == XmlNodeType.Element)
                {
                    if (textReader.Name == "fromWord")
                    {
                        fromWord = textReader.GetAttribute("name");
                    }
                    else if (textReader.Name == "toWord")
                    {
                        if (fromWord != null)
                        {
                            toWord = textReader.GetAttribute("name");
                            float.TryParse(textReader.GetAttribute("statisticValue"), out statisticValue);
                            matrix.SetStatistics(fromWord, toWord, statisticValue);
                        }
                    }
                }
            }

            textReader.Close();

            return matrix;
        }
Пример #27
0
 static XmlSchema GetEprSchema()
 {
     using (XmlTextReader reader = new XmlTextReader(new StringReader(Schema)) { DtdProcessing = DtdProcessing.Prohibit })
     {
         return XmlSchema.Read(reader, null);
     }
 }
 /// <summary> Reads the inner data from the Template XML format </summary>
 /// <param name="xmlReader"> Current template xml configuration reader </param>
 /// <remarks> This reads the possible values for the combo box from a <i>options</i> subelement and the default value from a <i>value</i> subelement </remarks>
 protected override void Inner_Read_Data( XmlTextReader xmlReader )
 {
     default_values.Clear();
     while ( xmlReader.Read() )
     {
         if (( xmlReader.NodeType == XmlNodeType.Element ) && (( xmlReader.Name.ToLower() == "value" ) || ( xmlReader.Name.ToLower() == "options" )))
         {
             if ( xmlReader.Name.ToLower() == "value" )
             {
                 xmlReader.Read();
                 default_values.Add(xmlReader.Value.Trim());
             }
             else
             {
                 xmlReader.Read();
                 string options = xmlReader.Value.Trim();
                 items.Clear();
                 if ( options.Length > 0 )
                 {
                     string[] options_parsed = options.Split(",".ToCharArray());
                     foreach (string thisOption in options_parsed.Where(thisOption => !items.Contains(thisOption.Trim())))
                     {
                         items.Add( thisOption.Trim() );
                     }
                 }
             }
         }
     }
 }
        public override WebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            XmlTextReader reader = new XmlTextReader(context.ResponseStream);
            SendMessageResponse response = new SendMessageResponse();

            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        switch (reader.LocalName)
                        {
                            case MNSConstants.XML_ELEMENT_MESSAGE_ID:
                                response.MessageId = reader.ReadElementContentAsString();
                                break;
                            case MNSConstants.XML_ELEMENT_MESSAGE_BODY_MD5:
                                response.MessageBodyMD5 = reader.ReadElementContentAsString();
                                break;
                        }
                        break;
                }
            }
            reader.Close();
            return response;
        }
 public RepertoireRepository()
 {
     XmlReader reader = new XmlTextReader(path);
     List<TheaterRepertoire> filereprt = (List<TheaterRepertoire>)writers.Deserialize(reader);
     reader.Close();
     this.repertoiresList = filereprt;
 }
Пример #31
0
        /// <summary>
        /// Extracts workspace settings from an XML Fragment and puts them into a hashtable:
        /// </summary>
        /// <param name="xmlFrag">The XML frag.</param>
        /// <returns>
        /// hashtable of the geodatabase workspace parameters
        /// </returns>
        private Hashtable WrkspcXMLFrag2Hash(string xmlFrag)
        {
            Trace.WriteLine("Start WrkspcXMLFrag2Hash");
            Hashtable hash = new Hashtable();

            try
            {
                NameTable           nameTable        = new NameTable();
                XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable());
                namespaceManager.AddNamespace("rk", "urn:store-items");

                XmlParserContext     parserContext = new XmlParserContext(null, namespaceManager, null, XmlSpace.None);
                System.Xml.XmlReader xmlReader     = new System.Xml.XmlTextReader(xmlFrag, XmlNodeType.Element, parserContext);

                // iterate through the attributes of the <WORKSPACE> XML fragment and load into hashtable:
                try
                {
                    while (xmlReader.Read())
                    {
                        if (xmlReader.NodeType == XmlNodeType.Element)
                        {
                            if (xmlReader.HasAttributes == true)
                            {
                                try
                                {
                                    while (xmlReader.MoveToNextAttribute())
                                    {
                                        hash.Add(xmlReader.Name.ToUpper(), xmlReader.Value);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Trace.WriteLine("ArcZonaWorkspace.WrkspcXMLFrag2Hash Exception  Inside While: " + ex.Message + "\n\nStackTrace: " + ex.StackTrace);
                                    throw;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("ArcZonaWorkspace.WrkspcXMLFrag2Hash Exception: " + ex.Message + "\n\nStackTrace: " + ex.StackTrace);
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine("ArcZonaWorkspace.WrkspcXMLFrag2Hash Exception: " + ex.Message + "\n\nStackTrace: " + ex.StackTrace);
                throw;
            }

            Trace.WriteLine("End WrkspcXMLFrag2Hash");

            return(hash);
        }
Пример #32
0
        public static T DeserializeDataContract <T>(string xml) where T : class
        {
            var serializer = new DataContractSerializer(typeof(T));

            using (var backing = new System.IO.StringReader(xml))
            {
                using (var reader = new System.Xml.XmlTextReader(backing))
                {
                    return(serializer.ReadObject(reader) as T);
                }
            }
        }
Пример #33
0
        void ReadXMLFile(string filename)
        {
            //load the xml file into the XmlTextReader object.
            XmlTextReader XmlRdr = new System.Xml.XmlTextReader(filename);

            //while moving through the xml document.
            bool ListIsReady = false;

            LyricObject myLyric = new LyricObject();

            while (XmlRdr.Read())
            {
                ListIsReady = true; // guard to make sure we have font objects to fill with data..


                if (ListIsReady)
                {
                    //check the node type and look for the elements desired.
                    if (XmlRdr.NodeType == XmlNodeType.Element && XmlRdr.Name == "Artist")
                    {
                        myLyric.Artist = XmlRdr.ReadElementContentAsString();
                    }

                    if (XmlRdr.NodeType == XmlNodeType.Element && XmlRdr.Name == "Title")
                    {
                        myLyric.Title = XmlRdr.ReadElementContentAsString();
                    }

                    if (XmlRdr.NodeType == XmlNodeType.Element && XmlRdr.Name == "S1")
                    {
                        myLyric.S1 = XmlRdr.ReadElementContentAsString();
                    }

                    if (XmlRdr.NodeType == XmlNodeType.Element && XmlRdr.Name == "S2")
                    {
                        myLyric.S2 = XmlRdr.ReadElementContentAsString();
                    }

                    if (XmlRdr.NodeType == XmlNodeType.Element && XmlRdr.Name == "S3")
                    {
                        myLyric.S3 = XmlRdr.ReadElementContentAsString();
                    }

                    if (XmlRdr.NodeType == XmlNodeType.Element && XmlRdr.Name == "S4")
                    {
                        myLyric.S4 = XmlRdr.ReadElementContentAsString();

                        m_LyricObject.Add(myLyric);
                        myLyric = new LyricObject();
                    }
                }
            } //endwhile
        }
Пример #34
0
        private void Conectar()
        {
            Connected = false;
            try
            {
                System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("c:\\Terminal.xml");
                IDTerminal = 0;
                while (reader.Read())
                {
                    switch (reader.Name)
                    {
                    case "Mensaje":
                        IDTerminal = Convert.ToInt16(reader.ReadString());
                        break;

                    case "IP":
                        IP = reader.ReadString();
                        break;

                    case "PUERTO":
                        Port = Convert.ToInt32(reader.ReadString());
                        break;
                    }
                }
                msj                = new Mensaje();
                Cliente            = new TcpClient(this.IP, this.Port);
                StreamCliente      = Cliente.GetStream();
                msj.NombreTerminal = "Terminal";
                msj.Prioridad      = IDTerminal;
                msj.op             = 4;
                Send s = Send.GetSend();
                s.StreamCliente = this.StreamCliente;
                s.Cliente       = this.Cliente;
                s.EnviarMensaje(serial.SerializarObj(msj));
                Connected = true;
                this.Hilo = new Thread(SubProceso);
                this.Hilo.IsBackground = true;
                this.Hilo.Start();
            }
            catch
            {
                DialogResult dialogResult = MessageBox.Show("Error 100 - Sin conexion al servidor ¿Intentar Reconectar?", "Sin conexion a el servidor", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    Conectar();
                }
                else if (dialogResult == DialogResult.No)
                {
                    Connected = false;
                    Application.Exit();
                }
            }
        }
Пример #35
0
        private void FillDataSetSeveralTables()
        {
            DataSet dsSource = new DataSet();

            System.IO.FileStream myFileStream = new System.IO.FileStream("factures.xsd", System.IO.FileMode.Open);

            // Create a new XmlTextReader object with the FileStream.
            System.Xml.XmlTextReader myXmlTextReader =
                new System.Xml.XmlTextReader(myFileStream);
            // Read the schema into the DataSet and close the reader.
            dsSource.ReadXmlSchema(myXmlTextReader);
            myXmlTextReader.Close();

            // Read the XML document back in.
            // Create new FileStream to read schema with.
            System.IO.FileStream fsReadXml = new System.IO.FileStream
                                                 ("factures.xml", System.IO.FileMode.Open);

            System.Xml.XmlTextReader myXmlReader = new System.Xml.XmlTextReader(fsReadXml);

            dsSource.ReadXml(myXmlReader);
            myXmlReader.Close();

            myFileStream = new System.IO.FileStream("clients.xsd", System.IO.FileMode.Open);

            // Create a new XmlTextReader object with the FileStream.
            myXmlTextReader =
                new System.Xml.XmlTextReader(myFileStream);
            // Read the schema into the DataSet and close the reader.
            dsSource.ReadXmlSchema(myXmlTextReader);
            myXmlTextReader.Close();

            fsReadXml = new System.IO.FileStream
                            ("clients.xml", System.IO.FileMode.Open);

            myXmlReader = new System.Xml.XmlTextReader(fsReadXml);

            dsSource.ReadXml(myXmlReader);
            myXmlReader.Close();

            DataTable factures = dsSource.Tables["Factures"];
            DataTable clients  = dsSource.Tables["Clients"];

            DataRelation rel = new DataRelation(null,
                                                new DataColumn [] { clients.Columns["Id"] },        // parent
                                                new DataColumn [] { factures.Columns["cliente"] }); // child, consumer

            dsSource.Relations.Add(rel);

            dataGrid.DataSource = dsSource;            //;.Tables["programes"];
            FillTree();
        }
Пример #36
0
        void RegisterSyntaxHighlighters()
        {
            using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("XSLTool.Resources.Highlighting.sql.xshd"))
            {
                using (var reader = new System.Xml.XmlTextReader(stream))
                {
                    var highlighting =
                        ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(reader, HighlightingManager.Instance);

                    HighlightingManager.Instance.RegisterHighlighting("SQL", null, highlighting);
                }
            }
        }
Пример #37
0
 static AmlSimpleEditorHelper()
 {
     using (var stream = System.Reflection.Assembly.GetExecutingAssembly()
                         .GetManifestResourceStream("InnovatorAdmin.resources.Aml.xshd"))
     {
         using (var reader = new System.Xml.XmlTextReader(stream))
         {
             _highlighter =
                 ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(reader,
                                                                                  ICSharpCode.AvalonEdit.Highlighting.HighlightingManager.Instance);
         }
     }
 }
Пример #38
0
        private void IniciarServidor()
        {
            int    Port = 0;
            string IP   = "";

            try
            {
                System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("c:\\Servidor.xml");
                while (reader.Read())
                {
                    switch (reader.Name)
                    {
                    case "IP":
                        IP = reader.ReadString();
                        break;

                    case "PUERTO":
                        Port = Convert.ToInt32(reader.ReadString());
                        break;
                    }
                }
            }
            catch
            {
                MessageBox.Show("Error al cargar configuracion de conexion");
            }
            try
            {
                IPEndPoint ipend = new IPEndPoint(IPAddress.Parse(IP), Port);
                Server = new TcpListener(ipend);
                Server.Start();
            }
            catch
            {
                DialogResult dialogResult = MessageBox.Show("Error al iniciar servidor ¿Intentar denuevo?", "Alerta", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    IniciarServidor();
                }
                else if (dialogResult == DialogResult.No)
                {
                    Application.Exit();
                }
            }
            hs = new Hashtable();
            datos.setTerminales(hs);
            this.Hilo = new Thread(ServerStart);
            this.Hilo.IsBackground = true;
            this.Hilo.Start();
            datos.Online = true;
        }
Пример #39
0
        void createHtmlFromXsl()
        {
            string resultDoc = projSettings.DestinationPath + projSettings.DocHtmlFileName;

            if (projSettings.StyleName == "OrteliusXml")
            {
                resultDoc = projSettings.DestinationPath + "/orteliusXml.xml";
            }
            string xmlDoc = projSettings.DestinationPath + projSettings.DocXmlFileName;
            string xslDoc = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "/styles/" + projSettings.StyleName + ".xsl";

            try
            {
                Processor processor                 = new Processor();
                System.IO.StreamReader reader       = new System.IO.StreamReader(xmlDoc, System.Text.Encoding.UTF8);
                System.IO.TextWriter   stringWriter = new System.IO.StringWriter();

                stringWriter.Write(reader.ReadToEnd());
                stringWriter.Close();

                reader.Close();

                System.IO.TextReader     stringReader = new System.IO.StringReader(stringWriter.ToString());
                System.Xml.XmlTextReader reader2      = new System.Xml.XmlTextReader(stringReader);
                reader2.XmlResolver = null;

                // Load the source document
                XdmNode input = processor.NewDocumentBuilder().Build(reader2);

                // Create a transformer for the stylesheet.
                XsltTransformer transformer = processor.NewXsltCompiler().Compile(new System.Uri(xslDoc)).Load();
                transformer.InputXmlResolver = null;

                // Set the root node of the source document to be the initial context node
                transformer.InitialContextNode = input;

                // Create a serializer
                Serializer serializer = new Serializer();

                serializer.SetOutputFile(resultDoc);

                // Transform the source XML to System.out.
                transformer.Run(serializer);
            }
            catch (Exception e)
            {
                //MessageBox.Show(e.ToString());
                systemSvar += "Error in xslt rendering:\r\n" + e.ToString();
            }
        }
    public static object FromXml(string Xml, Type t)
    {
        object        obj;
        XmlSerializer ser = new XmlSerializer(t);

        using (StringReader stringReader = new StringReader(Xml))
        {
            using (System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(stringReader))
            {
                obj = ser.Deserialize(xmlReader);
            }
        }
        return(obj);
    }
 /// <summary>
 /// Clase para Deserializar un String en formato Plain Old XML en una clase especificada.
 /// </summary>
 /// <typeparam name="T">Clase a Convertir.</typeparam>
 /// <param name="xmlSerializado">String en Formato Plain Old XML.</param>
 /// <returns>Data Casteada en la Clase indicada.</returns>
 public static T DeserializarTo <T>(this string xmlSerializado)
 {
     try
     {
         var serializer = new DataContractSerializer(typeof(T));
         using (var backing = new System.IO.StringReader(xmlSerializado))
             using (var reader = new System.Xml.XmlTextReader(backing))
             {
                 object obj = serializer.ReadObject(reader);
                 return((T)obj);
             }
     }
     catch { return(default(T)); }
 }
Пример #42
0
        /// <summary>
        /// Finner alle funksjoner som en bestemt variabel inngår i, og variabelens tilhørende beskrivelse. Hentes fra en C# xml fil.
        /// Dobbelarrayen har to kolonner. Første kolonne er funksjonsnavn, mens andre kolonne er variabelbeskrivelsen for hver funksjon.
        /// </summary>
        /// <param name="varNavn">Navnet på variabelen man vil ha info om.</param>
        /// <param name="fil">Full path med filnavn til xml filen.</param>
        /// <returns>Dobbelarrayen har to kolonner. Første kolonne er funksjonsnavn, mens andre kolonne er variabelbeskrivelsen for hver funksjon.</returns>
        public static string[,] XmlLesFunkNavnVarBeskFraVar(string varNavn, string fil)
        {
            Xml.XmlTextReader rd = new Xml.XmlTextReader(fil);
            System.Collections.Generic.List <string> varBeskLi  = new System.Collections.Generic.List <string>();
            System.Collections.Generic.List <string> funkNavnLi = new System.Collections.Generic.List <string>();
            string reg = "([.]\\w+([(]))"; //matcher punktum, etterfulgt av et ord, etterfulgt av parentesstart.

            while (rd.Read())
            {
                if (rd.Name == "member")
                { //Funksjonsnavn
                    string attr = "";
                    for (int j = 0; j < rd.AttributeCount; j++)
                    {
                        attr = rd.GetAttribute(0);                                         //Hvis jeg ikke har med for-løkken, så får jeg en feilmelding.
                    }
                    RegExp.Match m = RegExp.Regex.Match(attr, reg);
                    if (m.Success)
                    {
                        attr = m.ToString();
                        funkNavnLi.Add(attr.Remove(attr.Length - 1).Remove(0, 1)); //Fjerner punktum og parentes
                    }
                }
                else if (rd.Name == "param")
                { //Variabelbeskrivelse
                    string attr = "";
                    if (rd.AttributeCount > 0)
                    {
                        attr = rd.GetAttribute(0).Trim();                        //Det hender at rd ikke har noen attributes.
                    }
                    if (attr == varNavn)
                    {
                        varBeskLi.Add(rd.ReadString().Trim());
                    }
                }
            }
            rd.Close();
            if (string.IsNullOrEmpty(funkNavnLi[0]))
            {
                Console.WriteLine("Fant ikke variabelen " + varNavn + " i xmlfilen.");
                return(null);
            }
            string[,] funkNavnVarBeskLi = new string[funkNavnLi.Count, 2];
            for (int i = 0; i < funkNavnVarBeskLi.GetLength(0); i++)
            {
                funkNavnVarBeskLi[i, 0] = funkNavnLi[i];
                funkNavnVarBeskLi[i, 1] = varBeskLi[i];
            }
            return(funkNavnVarBeskLi);
        }
Пример #43
0
        private static bool EsCFDIXmlValido(List <String> PathsXSD, System.IO.StringReader XMLPath, out List <string> Errores)
        {
            try
            {
                // 0- Initialize variables...
                _IsValid  = true;
                Resultado = new List <string>();


                // 1- Read XML file content
                Reader = new System.Xml.XmlTextReader(XMLPath);

                // 3- Create a new instance of XmlSchema object
                System.Xml.Schema.XmlSchema  Schema         = new System.Xml.Schema.XmlSchema();
                System.Xml.XmlReaderSettings ReaderSettings = new System.Xml.XmlReaderSettings();

                // 2- Read Schema file content
                foreach (String XSD in PathsXSD)
                {
                    StreamReader SR = new StreamReader(XSD);
                    Schema = System.Xml.Schema.XmlSchema.Read(SR, new System.Xml.Schema.ValidationEventHandler(ReaderSettings_ValidationEventHandler));
                    ReaderSettings.ValidationType = System.Xml.ValidationType.Schema;
                    ReaderSettings.Schemas.Add(Schema);
                }
                // 8- Add your ValidationEventHandler address to
                // XmlReaderSettings ValidationEventHandler
                ReaderSettings.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(ReaderSettings_ValidationEventHandler);

                // 9- Create a new instance of XmlReader object
                System.Xml.XmlReader objXmlReader = System.Xml.XmlReader.Create(Reader, ReaderSettings);

                // 10- Read XML content in a loop
                while (objXmlReader.Read())
                {
                    // empty loop
                }

                // Se cierra el validador
                objXmlReader.Close();
                Errores = Resultado;
                return(_IsValid);
            }
            catch (Exception ex)
            {
                Errores = new List <string>();
                Errores.Add("Error de validacion del XML Error:" + ex.ToString());
                return(true);
            }
        }
Пример #44
0
        public static bool VerifyFileFormat(string convertedCadFilePath)
        {
            bool isValid       = true;
            var  xmlTextReader = new System.Xml.XmlTextReader(convertedCadFilePath);

            xmlTextReader.MoveToContent();
            if (!String.Equals(xmlTextReader.LocalName, "Model3DGroup", StringComparison.CurrentCultureIgnoreCase))
            {
                isValid = false;
                throw new Exception("Failed...");
            }
            xmlTextReader.Close();

            return(isValid);
        }
Пример #45
0
        internal void DoPreview(string title)
        {
            string fileName = System.IO.Path.GetRandomFileName();

            try
            {
                // write the XPS document
                using (XpsDocument doc = new XpsDocument(fileName, FileAccess.ReadWrite))
                {
                    XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);
                    writer.Write(selCanv);
                }

                // Read the XPS document into a dynamically generated
                // preview Window
                using (XpsDocument doc = new XpsDocument(fileName, FileAccess.Read))
                {
                    FixedDocumentSequence fds = doc.GetFixedDocumentSequence();

                    string s = _previewWindowXaml;
                    s = s.Replace("@@TITLE", title.Replace("'", "&apos;"));

                    using (var reader = new System.Xml.XmlTextReader(new StringReader(s)))
                    {
                        Window preview = System.Windows.Markup.XamlReader.Load(reader) as Window;

                        DocumentViewer dv1 = LogicalTreeHelper.FindLogicalNode(preview, "dv1") as DocumentViewer;
                        dv1.Document = fds as IDocumentPaginatorSource;


                        preview.ShowDialog();
                    }
                }
            }
            finally
            {
                if (File.Exists(fileName))
                {
                    try
                    {
                        File.Delete(fileName);
                    }
                    catch
                    {
                    }
                }
            }
        }
Пример #46
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="highlight">A stream that contains xshd formatted highlight instructions.</param>
        public EditorSettings(string settingName, Stream highlight)
        {
            if (String.IsNullOrWhiteSpace(settingName))
            {
                throw new ArgumentException("settingName is null or whitespace.", "settingName");
            }
            if (highlight == null)
            {
                throw new ArgumentNullException("highlight");
            }

            _settingName = settingName;

            using (System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(highlight))
                HighlightDefinition = HighlightingLoader.Load(reader, HighlightingManager.Instance);

            Symbols = new List <EditorSymbolSettings>();

            FontFamily           = new FontFamily("Consolas");
            FontSizeInPoints     = 10;
            Foreground           = Colors.Black;
            Background           = Colors.White;
            SelectionForeground  = null;
            SelectionBackground  = Colors.LightBlue;
            FindResultBackground = Colors.DarkOrange;

            if (!Load())
            {
                List <EditorSymbolSettings> symbols = new List <EditorSymbolSettings>();
                foreach (HighlightingColor hc in HighlightDefinition.NamedHighlightingColors)
                {
                    EditorSymbolSettings ess = new EditorSymbolSettings(hc.Name);
                    ess.Foreground = (hc.Foreground != null) ? hc.Foreground.GetColor(null) : null;
                    ess.Background = (hc.Background != null) ? hc.Background.GetColor(null) : null;
                    ess.Weight     = hc.FontWeight;
                    ess.Style      = hc.FontStyle;
                    ess.Commit();
                    symbols.Add(ess);
                }
                Symbols = symbols;
            }
            else
            {
                ApplySymbolUpdates();
            }

            Themes = new List <EditorSettingsTheme>();
        }
Пример #47
0
        //'/primepractice/clinical/stylesheets/labresult.xsl      'Regular Result
        //'/primepractice/clinical/stylesheets/labdocument.xsl    'Microbiology
        //'/primepractice/clinical/stylesheets/document.xsl       'Transcription
        public static string TranslateLabResultXMLToMobileHTML(string sXML, string sStyleSheetType)
        {
            try
            {
                System.Xml.Xsl.XslCompiledTransform xsltTransform = new System.Xml.Xsl.XslCompiledTransform();
                System.IO.StreamReader xsltStream;

                switch (sStyleSheetType.ToLower())
                {
                case "document":
                    xsltStream = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("MobileDocument.xslt"));
                    break;

                case "labdocument":
                    xsltStream = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("MobileLabDocument.xslt"));
                    break;

                case "labresult":
                    xsltStream = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("MobileLabResult.xslt"));
                    break;

                default:
                    xsltStream = null;
                    break;
                }

                System.Xml.XmlTextReader xtextreader = new System.Xml.XmlTextReader(xsltStream);
                xsltTransform.Load(xtextreader);

                System.Xml.XmlDocument xLabResultDom = new System.Xml.XmlDocument();
                xLabResultDom.LoadXml(sXML);

                System.Xml.XmlWriterSettings xWriterSettings = new System.Xml.XmlWriterSettings();
                xWriterSettings.ConformanceLevel = System.Xml.ConformanceLevel.Auto;

                StringBuilder sb = new StringBuilder();

                //Dim xDoc As New System.Xml.XPath.XPathDocument(New System.IO.StringReader(sXML))
                //'xsltTransform.Transform(xDoc, System.Xml.XmlWriter.Create(sb, xWriterSettings))
                xsltTransform.Transform(new System.Xml.XmlNodeReader(xLabResultDom), System.Xml.XmlWriter.Create(sb, xWriterSettings));

                return(sb.ToString());
            }
            catch (Exception ex)
            {
                throw new Exception("Exception in Sirona.Utilities.Translator.TranslateLabResultXMLToMobileHTML:  \n" + ex.Message);
            }
        }
Пример #48
0
 public bool XMLTagExists(string FilePath, string SearchTag)
 {
     System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(FilePath);
     while (reader.Read())
     {
         reader.MoveToContent();
         if (reader.NodeType == System.Xml.XmlNodeType.Element)
         {
             if (reader.Name == SearchTag)
             {
                 return(true);
             }
         }
     }
     return(false);
 }
Пример #49
0
        public void SpecialCharactersInMetadataValueConstruction()
        {
            string projectString = ObjectModelHelpers.CleanupFileContents(@"<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
    <ItemGroup>
        <None Include='MetadataTests'>
            <EscapedSemicolon>%3B</EscapedSemicolon>
            <EscapedDollarSign>%24</EscapedDollarSign>
        </None>
    </ItemGroup>
</Project>");

            System.Xml.XmlReader reader = new System.Xml.XmlTextReader(new StringReader(projectString));
            Microsoft.Build.Evaluation.Project     project = new Microsoft.Build.Evaluation.Project(reader);
            Microsoft.Build.Evaluation.ProjectItem item    = project.GetItems("None").Single();

            SpecialCharactersInMetadataValueTests(item);
        }
Пример #50
0
        public static T Deserialize <T>(string xml)
        {
            if (string.IsNullOrEmpty(xml))
            {
                throw new ArgumentNullException("xml");
            }

            var serializer = new DataContractSerializer(typeof(T));

            using (var backing = new System.IO.StringReader(xml))
            {
                using (var reader = new System.Xml.XmlTextReader(backing))
                {
                    return((T)serializer.ReadObject(reader));
                }
            }
        }
Пример #51
0
        private void readDictionaryFile(string filename)
        {
            try
            {
                // Read the XML document back in.
                System.IO.FileStream     fsReadXml   = new System.IO.FileStream(filename, System.IO.FileMode.Open);
                System.Xml.XmlTextReader myXmlReader = new System.Xml.XmlTextReader(fsReadXml);
                dictionaryDataSet.ReadXml(myXmlReader, XmlReadMode.IgnoreSchema);                               // we already have schema
                myXmlReader.Close();

                dictionaryDataSet.AcceptChanges();
            }
            catch
            {
                LibSys.StatusBar.Error("bad dictionary at " + filename);
            }
        }
Пример #52
0
        /// <summary>
        /// XML字符转换成DataSet
        /// </summary>
        /// <param name="xmlStr">xml字符串</param>
        /// <returns></returns>
        public DataSet XmlToDataSet(string xmlStr)
        {
            try
            {
                if (!string.IsNullOrEmpty(xmlStr))
                {
                    StringReader             StrStream = null;
                    System.Xml.XmlTextReader Xmlrdr    = null;
                    try
                    {
                        DataSet ds = new DataSet();
                        //读取字符串中的信息
                        StrStream = new StringReader(xmlStr);
                        //获取StrStream中的数据
                        Xmlrdr = new System.Xml.XmlTextReader(StrStream);
                        //ds获取Xmlrdr中的数据
                        ds.ReadXml(Xmlrdr);

                        return(ds);
                    }
                    catch (Exception e)
                    {
                        return(null);
                    }
                    finally
                    {
                        //释放资源
                        if (Xmlrdr != null)
                        {
                            Xmlrdr.Close();
                            StrStream.Close();
                            StrStream.Dispose();
                        }
                    }
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception)
            {
                return(null);
            }
        }
Пример #53
0
        public string TransformXML(string xml, string xsl)
        {
            System.IO.StringReader          stringReader        = null;
            System.Xml.Xsl.XslTransform     xslTransform        = null;
            System.Xml.XmlTextReader        xmlTextReader       = null;
            System.IO.MemoryStream          xmlTextWriterStream = null;
            System.Xml.XmlTextWriter        xmlTextWriter       = null;
            System.Xml.XmlDocument          xmlDocument         = null;
            System.IO.StreamReader          streamReader        = null;
            System.Security.Policy.Evidence evidence            = null;
            try
            {
                stringReader        = new System.IO.StringReader(xsl);
                xslTransform        = new System.Xml.Xsl.XslTransform();
                xmlTextReader       = new System.Xml.XmlTextReader(stringReader);
                xmlTextWriterStream = new System.IO.MemoryStream();
                xmlTextWriter       = new System.Xml.XmlTextWriter(xmlTextWriterStream, System.Text.Encoding.Default);
                xmlDocument         = new System.Xml.XmlDocument();

                evidence = new System.Security.Policy.Evidence();
                evidence.AddAssembly(this);
                xmlDocument.LoadXml(xml);
                xslTransform.Load(xmlTextReader, null, evidence);
                xslTransform.Transform(xmlDocument, null, xmlTextWriter, null);
                xmlTextWriter.Flush();

                xmlTextWriterStream.Position = 0;
                streamReader = new System.IO.StreamReader(xmlTextWriterStream);
                return(streamReader.ReadToEnd());
            }
            catch (Exception exc)
            {
                LogEvent(exc.Source, "TransformXML()", exc.ToString(), 4);
                return("");
            }
            finally
            {
                streamReader.Close();
                xmlTextWriter.Close();
                xmlTextWriterStream.Close();
                xmlTextReader.Close();
                stringReader.Close();
                GC.Collect();
            }
        }
        internal static void Open(string path, Scene scene, TextureManager textureManager, Layers layers)
        {
            XmlTextReader xmlReader = new System.Xml.XmlTextReader(path);

            xmlReader.MoveToContent();  // Jumps into top level header
            while (xmlReader.Read())
            {
                if ("texturedata" == xmlReader.Name)
                {
                    LoadTextureData(xmlReader, textureManager);
                }
                else if ("scenedata" == xmlReader.Name)
                {
                    LoadSceneData(xmlReader, scene, textureManager);
                }
            }
            layers.RefreshLayerContent(scene.Layers);
        }
Пример #55
0
        public static void SetEditorSkin(TextEditor editor, HandyControl.Data.SkinType skin)
        {
            //light
            if (skin == HandyControl.Data.SkinType.Default || skin == HandyControl.Data.SkinType.Violet)
            {
                //theme
                editor.LineNumbersForeground =
                    new Win.Media.SolidColorBrush(Win.Media.Color.FromRgb(100, 100, 100));
                editor.Background =
                    new Win.Media.SolidColorBrush(Win.Media.Color.FromRgb(250, 250, 250));
                editor.Foreground =
                    new Win.Media.SolidColorBrush(Win.Media.Color.FromRgb(12, 12, 12));
                //syntax
                using (IO.Stream stream = Win.Application.GetResourceStream(new Uri(
                                                                                "pack://application:,,/Editor/LightSyntax.xshd", UriKind.RelativeOrAbsolute)).Stream)
                {
                    using (XML.XmlTextReader reader = new XML.XmlTextReader(stream))
                    {
                        editor.SyntaxHighlighting = ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(reader, HighlightingManager.Instance);
                    }
                }
            }
            //dark
            else
            {
                //theme
                editor.LineNumbersForeground =
                    new Win.Media.SolidColorBrush(Win.Media.Color.FromRgb(43, 145, 175));
                editor.Background =
                    new Win.Media.SolidColorBrush(Win.Media.Color.FromRgb(30, 30, 30));
                editor.Foreground =
                    new Win.Media.SolidColorBrush(Win.Media.Color.FromRgb(220, 220, 220));

                //syntax
                using (IO.Stream stream = Win.Application.GetResourceStream(new Uri(
                                                                                "pack://application:,,/Editor/DarkSyntax.xshd", UriKind.RelativeOrAbsolute)).Stream)
                {
                    using (XML.XmlTextReader reader = new XML.XmlTextReader(stream))
                    {
                        editor.SyntaxHighlighting = ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(reader, HighlightingManager.Instance);
                    }
                }
            }
        }
    public void LoadCar(bool wet)
    {
        var settings     = GetComponent <DriveAdminUISettings>();
        var configurator = settings.configurator;

        var car = AppController.Instance.currentSessionSettings.selectedCarShortname;

        var serializer = new XmlSerializer(typeof(VehicleSettings));

        using (var filestream = new FileStream(Application.streamingAssetsPath + "/SavedPresets/" + car + (wet ? "_WET.xml" : ".xml"), FileMode.Open))
        {
            var reader        = new System.Xml.XmlTextReader(filestream);
            var savedSettings = serializer.Deserialize(reader) as VehicleSettings;
            savedSettings.Apply(configurator);
        }

        //refresh vehicle panel info
        adminCategories[4].UpdateValues();
    }
Пример #57
0
        private void PlayEpisode(int episode, AxShockwaveFlashObjects.AxShockwaveFlash FlashControl) //Odtwórz odcinek
        {
            Control[] Cont = { btnPlay, cmbBox, linkLabel1, Stan, menuStrip1, btnToHTML, btnEpisodesList };
            System.Xml.XmlTextReader XMLTxtReader = new System.Xml.XmlTextReader(Friends_from_MegaVideo_player.Properties.Settings.Default.FilePath);
            System.Xml.XmlDocument   XMLDoc       = new System.Xml.XmlDocument();
            XMLDoc.Load(XMLTxtReader);
            XMLTxtReader.Close();
            XmlNodeList nl = XMLDoc.SelectNodes("/Spis/Odcinek/NazwaOdcinka");

            Friends_from_MegaVideo_player.Properties.Settings.Default.Ostatni = episode;
            Friends_from_MegaVideo_player.Properties.Settings.Default.Save();
            this.Focus();
            if ((episode < 239) | (episode > 0))
            {
                foreach (XmlNode n in nl)
                {
                    if (n.NextSibling.NextSibling.NextSibling.InnerText == episode.ToString())                                                     //Szuka odcinka o takiej samej nazwie jak ta wyciągnięta z pliku XML
                    {
                        FlashControl.Movie = (n.NextSibling.NextSibling.NextSibling.NextSibling.InnerText);                                        //Wyciągnięcie linku z pliku
                        this.Text          = "Przyjaciele Player - " + n.InnerText + " (" + n.NextSibling.NextSibling.NextSibling.InnerText + ")"; //Ustawienie nagłówka
                        KontrolkiVisible(false, Cont);
                        this.ClientSize   = new Size(640, 481);
                        FlashControl.Size = new Size(640, 481);
                        frm.Maximize(this);
                        this.Focus();
                        break;
                    }
                }
            }
            if (episode == 239)
            {
                MessageBox.Show("To był już ostatni odcinek!");
                Friends_from_MegaVideo_player.Properties.Settings.Default.Ostatni = 238;
                Friends_from_MegaVideo_player.Properties.Settings.Default.Save();
            }
            if (episode == 0)
            {
                MessageBox.Show("To był pierwszy odcinek!");
                Friends_from_MegaVideo_player.Properties.Settings.Default.Ostatni = 1;
                Friends_from_MegaVideo_player.Properties.Settings.Default.Save();
            }
            this.Focus();
        }
Пример #58
0
        private bool ReadXMLFile(string fileName)
        {
            try
            {
                Logger.MajorDebug("Reading XML configuration...");
                System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(fileName);
                reader.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
                reader.MoveToContent();
                reader.Read();

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

                doc.Load(reader);

                port                   = Convert.ToInt32(GetParameterValue(doc, "Port"));
                consolePort            = Convert.ToInt32(GetParameterValue(doc, "ConsolePort"));
                maxCons                = Convert.ToInt32(GetParameterValue(doc, "MaxConnections"));
                LMKFile                = Convert.ToString(GetParameterValue(doc, "LMKStorageFile"));
                VBsources              = Convert.ToString(GetParameterValue(doc, "VBSourceDirectory"));
                Logger.CurrentLogLevel = (Log.Logger.LogLevel)(Enum.Parse(typeof(Logger.LogLevel), Convert.ToString(GetParameterValue(doc, "LogLevel")), true));
                CheckLMKParity         = Convert.ToBoolean(GetParameterValue(doc, "CheckLMKParity"));
                HostDefsDir            = Convert.ToString(GetParameterValue(doc, "XMLHostDefinitionsDirectory"));
                DoubleLengthZMKs       = Convert.ToBoolean(GetParameterValue(doc, "DoubleLengthZMKs"));
                LegacyMode             = Convert.ToBoolean(GetParameterValue(doc, "LegacyMode"));
                ExpectTrailers         = Convert.ToBoolean(GetParameterValue(doc, "ExpectTrailers"));
                HeaderLength           = Convert.ToInt32(GetParameterValue(doc, "HeaderLength"));
                EBCDIC                 = Convert.ToBoolean(GetParameterValue(doc, "EBCDIC"));

                StartUpCore(Convert.ToString(GetParameterValue(doc, "FirmwareNumber")), Convert.ToString(GetParameterValue(doc, "DSPFirmwareNumber")),
                            Convert.ToBoolean(GetParameterValue(doc, "StartInAuthorizedState")), Convert.ToInt32(GetParameterValue(doc, "ClearPINLength")));

                reader.Close();
                reader = null;

                return(true);
            }
            catch (Exception ex)
            {
                Logger.MajorError("Error loading the configuration file");
                Logger.MajorError(ex.ToString());
                return(true);
            }
        }
Пример #59
0
        public bool get(string filePath)
        {
            bool status = false;

            System.Xml.XmlTextReader reader;

            try
            {
                reader = new System.Xml.XmlTextReader(filePath);

                //string contents = "";

                string keyName = "";

                string keyVal = "";

                while (reader.Read())
                {
                    reader.MoveToContent();
                    if (reader.NodeType == System.Xml.XmlNodeType.Element)
                    {
                        keyName = reader.Name;
                    }
                    //contents += "<" + reader.Name + ">\n";

                    if (reader.NodeType == System.Xml.XmlNodeType.Text)
                    {
                        keyVal = reader.Value;
                    }
                    //contents += reader.Value + "\n";
                }

                status = true;
            }
            catch (Exception ex)
            {
                message = ex.Message;
                status  = false;
            }

            return(status);
        }
Пример #60
0
    // <Snippet1>
    private void ReadSchemaFromXmlTextReader()
    {
        // Create the DataSet to read the schema into.
        DataSet thisDataSet = new DataSet();

        // Set the file path and name. Modify this for your purposes.
        string filename = "Schema.xml";

        // Create a FileStream object with the file path and name.
        System.IO.FileStream stream = new System.IO.FileStream
                                          (filename, System.IO.FileMode.Open);

        // Create a new XmlTextReader object with the FileStream.
        System.Xml.XmlTextReader xmlReader =
            new System.Xml.XmlTextReader(stream);

        // Read the schema into the DataSet and close the reader.
        thisDataSet.ReadXmlSchema(xmlReader);
        xmlReader.Close();
    }