Exemplo n.º 1
0
    public Mirror(string spec)
    {
        objectStack = new Stack();
        objectStack.Push(null);

        // Register the commands
        commands = new List<Command>();
        commands.Add(new ElementCommand());
        commands.Add(new EndElementCommand());
        commands.Add(new AttributeCommand());

        Reader = new XmlTextReader(spec);
        while (Reader.Read())
        {
            InterpretCommands();

            var b = Reader.IsEmptyElement;
            if (Reader.HasAttributes)
            {
                for (var i = 0; i < Reader.AttributeCount; i++)
                {
                    Reader.MoveToAttribute(i);
                    InterpretCommands();
                }
            }
            if (b) Pop();
        }
    }
    public PlatformBuildSettings(XmlTextReader reader)
    {
        textureSettings = new List<TextureAssetSettings>(20);

        if(reader.MoveToAttribute("name"))
            platform = (Platform) System.Enum.Parse(typeof(Platform), reader.Value);
        while(reader.Read()) {
            if(reader.NodeType == XmlNodeType.EndElement && reader.Name == "Platform") {
                reader.ReadEndElement();
                break;
            }
            if(reader.NodeType == XmlNodeType.Element && reader.Name == "TextureAsset") {
                textureSettings.Add(new TextureAssetSettings(reader));
            }
        }
    }
 public TextureAssetSettings(XmlTextReader reader)
 {
     if(reader.MoveToAttribute("path"))
         path = reader.Value;
     while(reader.Read()) {
         if(reader.NodeType == XmlNodeType.EndElement && reader.Name == "TextureAsset") {
             reader.ReadEndElement();
             break;
         }
         if(reader.NodeType == XmlNodeType.Element && reader.Name == "maxSize") {
             maxSize = int.Parse(reader.ReadInnerXml());
         } else if(reader.NodeType == XmlNodeType.Element && reader.Name == "format") {
             format = (TextureImporterFormat) System.Enum.Parse(typeof(TextureImporterFormat), reader.ReadInnerXml());
         } else if(reader.NodeType == XmlNodeType.Element && reader.Name == "mipmaps") {
             mipmaps = bool.Parse(reader.ReadInnerXml());
         } else if(reader.NodeType == XmlNodeType.Element && reader.Name == "npotScale") {
             npotScale = (TextureImporterNPOTScale) System.Enum.Parse(typeof(TextureImporterNPOTScale), reader.ReadInnerXml());
         }
     }
 }
Exemplo n.º 4
0
 // we have to write this method ourselves, since it's
 // not provided by the API
 public virtual void Parse(string url)
 {
     try
     {
         XmlTextReader reader = new XmlTextReader(url);
         while (reader.Read())
         {
             switch (reader.NodeType)
             {
                 case XmlNodeType.Element:
                     string namespaceURI = reader.NamespaceURI;
                     string name = reader.Name;
                     Dictionary<String, String> att = new Dictionary<String, String>();
                     if (reader.HasAttributes)
                     {
                         for (int i = 0; i < reader.AttributeCount; i++)
                         {
                             reader.MoveToAttribute(i);
                             att.Add(reader.Name.ToString(), reader.Value.ToString());
                         }
                     }
                     startElement(namespaceURI, name, name, att);
                     break;
                 case XmlNodeType.EndElement:
                     endElement(reader.NamespaceURI,
                            reader.Name, reader.Name);
                     break;
                 case XmlNodeType.Text:
                     //Debug.Log("TEXT: " + reader.Value);
                     characters(reader.Value.ToCharArray(), 0, reader.Value.Length);
                     break;
                     // There are many other types of nodes, but
                     // we are not interested in them
             }
         }
     }
     catch (XmlException e)
     {
         Console.WriteLine(e.Message);
     }
 }
Exemplo n.º 5
0
        public override IProblemData LoadData(IDataDescriptor descriptor)
        {
            var values = new List <IList>();
            var tList  = new List <DateTime>();
            var dList  = new List <double>();

            values.Add(tList);
            values.Add(dList);
            using (var client = new WebClient()) {
                var s = client.OpenRead("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.xml");
                if (s != null)
                {
                    using (var reader = new XmlTextReader(s)) {
                        reader.MoveToContent();
                        reader.ReadToDescendant("Cube", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");
                        reader.ReadToDescendant("Cube", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");
                        // foreach time
                        do
                        {
                            reader.MoveToAttribute("time");
                            tList.Add(reader.ReadContentAsDateTime());
                            reader.MoveToElement();
                            reader.ReadToDescendant("Cube", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");
                            // foreach currencys
                            do
                            {
                                // find matching entry
                                if (descriptor.Name.Contains(reader.GetAttribute("currency")))
                                {
                                    reader.MoveToAttribute("rate");
                                    dList.Add(reader.ReadContentAsDouble());

                                    reader.MoveToElement();
                                    // skip remaining siblings
                                    while (reader.ReadToNextSibling("Cube", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref"))
                                    {
                                        ;
                                    }
                                    break;
                                }
                            } while (reader.ReadToNextSibling("Cube", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref"));
                        } while (reader.ReadToNextSibling("Cube", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref"));
                    }
                }
            }
            // keep only the rows with data for this exchange rate
            if (tList.Count > dList.Count)
            {
                tList.RemoveRange(dList.Count, tList.Count - dList.Count);
            }
            else if (dList.Count > tList.Count)
            {
                dList.RemoveRange(tList.Count, dList.Count - tList.Count);
            }

            // entries in ECB XML are ordered most recent first => reverse lists
            tList.Reverse();
            dList.Reverse();

            // calculate exchange rate deltas
            var changes = new[] { 0.0 } // first element
            .Concat(dList.Zip(dList.Skip(1), (prev, cur) => cur - prev)).ToList();

            values.Add(changes);

            var targetVariable        = "d(" + descriptor.Name + ")";
            var allowedInputVariables = new string[] { targetVariable };

            var ds = new Dataset(new string[] { "Day", descriptor.Name, targetVariable }, values);

            return(new ProblemData(ds, allowedInputVariables, targetVariable));
        }
Exemplo n.º 6
0
        /// <summary>
        /// Gets an ordered array of .hbm.xml files that contain classes and an array that contains no classes
        /// </summary>
        /// <param name="classEntries">an ordered list of class entries</param>
        /// <param name="nonClassFiles">a list of files that do not contain classes.  These extra files may define filters, etc.
        /// that are being used by the classes</param>
        private void GetHbmFiles(out ArrayList classEntries, out ArrayList nonClassFiles)
        {
            HashedSet classes = new HashedSet();

            // tracks if any hbm.xml files make use of the "extends" attribute
            bool containsExtends = false;

            // tracks any extra files, i.e. those that do not contain a class definition.
            ArrayList extraFiles = new ArrayList();

            foreach (Assembly assembly in _assemblies)
            {
                foreach (string fileName in assembly.GetManifestResourceNames())
                {
                    if (!fileName.EndsWith(".hbm.xml"))
                    {
                        continue;
                    }

                    bool fileContainsClasses = false;

                    using (Stream xmlInputStream = assembly.GetManifestResourceStream(fileName))
                    {
                        // XmlReader does not implement IDisposable on .NET 1.1 so have to use
                        // try/finally instead of using here.
                        XmlTextReader xmlReader = new XmlTextReader(xmlInputStream);

                        string assemblyName = null;
                        string @namespace   = null;

                        try
                        {
                            while (xmlReader.Read())
                            {
                                if (xmlReader.NodeType != XmlNodeType.Element)
                                {
                                    continue;
                                }

                                switch (xmlReader.Name)
                                {
                                case "hibernate-mapping":
                                    assemblyName = xmlReader.MoveToAttribute("assembly") ? xmlReader.Value : null;
                                    @namespace   = xmlReader.MoveToAttribute("namespace") ? xmlReader.Value : null;
                                    break;

                                case "class":
                                case "joined-subclass":
                                case "subclass":
                                case "union-subclass":
                                    ClassEntry ce = BuildClassEntry(xmlReader, fileName, assemblyName, @namespace, assembly);
                                    classes.Add(ce);
                                    fileContainsClasses = true;
                                    containsExtends     = containsExtends || ce.FullExtends != null;
                                    break;
                                }

                                // no need to keep reading, since we already know the file contains classes
                                //if (fileContainsClasses)
                                //    break;
                            }
                        }
                        finally
                        {
                            xmlReader.Close();
                        }
                    }

                    if (!fileContainsClasses)
                    {
                        extraFiles.Add(new NonClassEntry(fileName, assembly));
                    }
                }
            }

            // only bother to do the sorting if one of the hbm files uses 'extends' -
            // the sorting does quite a bit of looping through collections so if we don't
            // need to spend the time doing that then don't bother.
            if (containsExtends)
            {
                // Add ordered hbms *after* the extra files, so that the extra files are processed first.
                // This may be useful if the extra files define filters, etc. that are being used by
                // the entity mappings.
                classEntries = OrderedHbmFiles(classes);
            }
            else
            {
                ArrayList unSortedList = new ArrayList();
                unSortedList.AddRange(classes);
                classEntries = unSortedList;
            }

            nonClassFiles = extraFiles;
        }
Exemplo n.º 7
0
 protected override bool EvaluateXmlElement(XmlTextReader xml)
 {
     return(xml.MoveToAttribute("missing"));
 }
        static void TryIndent(ITextEditor editor, int begin, int end)
        {
            string         currentIndentation = "";
            Stack <string> tagStack           = new Stack <string>();
            IDocument      document           = editor.Document;

            string      tab             = editor.Options.IndentationString;
            int         nextLine        = begin; // in #dev coordinates
            bool        wasEmptyElement = false;
            XmlNodeType lastType        = XmlNodeType.XmlDeclaration;

            using (StringReader stringReader = new StringReader(document.Text)) {
                XmlTextReader r = new XmlTextReader(stringReader);
                r.XmlResolver = null;                 // prevent XmlTextReader from loading external DTDs
                while (r.Read())
                {
                    if (wasEmptyElement)
                    {
                        wasEmptyElement = false;
                        if (tagStack.Count == 0)
                        {
                            currentIndentation = "";
                        }
                        else
                        {
                            currentIndentation = tagStack.Pop();
                        }
                    }
                    if (r.NodeType == XmlNodeType.EndElement)
                    {
                        if (tagStack.Count == 0)
                        {
                            currentIndentation = "";
                        }
                        else
                        {
                            currentIndentation = tagStack.Pop();
                        }
                    }

                    while (r.LineNumber >= nextLine)
                    {
                        if (nextLine > end)
                        {
                            break;
                        }
                        if (lastType == XmlNodeType.CDATA || lastType == XmlNodeType.Comment)
                        {
                            nextLine++;
                            continue;
                        }
                        // set indentation of 'nextLine'
                        IDocumentLine line     = document.GetLine(nextLine);
                        string        lineText = document.GetText(line);

                        string newText;
                        // special case: opening tag has closing bracket on extra line: remove one indentation level
                        if (lineText.Trim() == ">")
                        {
                            newText = tagStack.Peek() + lineText.Trim();
                        }
                        else
                        {
                            newText = currentIndentation + lineText.Trim();
                        }

                        document.SmartReplaceLine(line, newText);
                        nextLine++;
                    }
                    if (r.LineNumber > end)
                    {
                        break;
                    }
                    wasEmptyElement = r.NodeType == XmlNodeType.Element && r.IsEmptyElement;
                    string attribIndent = null;
                    if (r.NodeType == XmlNodeType.Element)
                    {
                        tagStack.Push(currentIndentation);
                        if (r.LineNumber < begin)
                        {
                            currentIndentation = DocumentUtilities.GetIndentation(editor.Document, r.LineNumber);
                        }
                        if (r.Name.Length < 16)
                        {
                            attribIndent = currentIndentation + new string(' ', 2 + r.Name.Length);
                        }
                        else
                        {
                            attribIndent = currentIndentation + tab;
                        }
                        currentIndentation += tab;
                    }
                    lastType = r.NodeType;
                    if (r.NodeType == XmlNodeType.Element && r.HasAttributes)
                    {
                        int startLine = r.LineNumber;
                        r.MoveToAttribute(0);                         // move to first attribute
                        if (r.LineNumber != startLine)
                        {
                            attribIndent = currentIndentation;                             // change to tab-indentation
                        }
                        r.MoveToAttribute(r.AttributeCount - 1);
                        while (r.LineNumber >= nextLine)
                        {
                            if (nextLine > end)
                            {
                                break;
                            }
                            // set indentation of 'nextLine'
                            IDocumentLine line    = document.GetLine(nextLine);
                            string        newText = attribIndent + document.GetText(line).Trim();
                            document.SmartReplaceLine(line, newText);
                            nextLine++;
                        }
                    }
                }
                r.Close();
            }
        }
Exemplo n.º 9
0
        public bool CarregarXML(string caminho, string database, int Codigo)
        {
            R2060           r2060           = new R2060();
            R2060infoProc   r2060InfoProc   = new R2060infoProc();
            R2060tipoAjuste r2060TipoAjuste = new R2060tipoAjuste();
            R2060tipoCod    r2060TipoCod    = new R2060tipoCod();

            DaoR2060           daoR2060           = new DaoR2060();
            DaoR2060infoProc   daoR2060InfoProc   = new DaoR2060infoProc();
            DaoR2060tipoAjuste daoR2060TipoAjuste = new DaoR2060tipoAjuste();
            DaoR2060tipoCod    daoR2060TipoCod    = new DaoR2060tipoCod();

            XmlDocument   xml = new XmlDocument();
            XmlTextReader x   = new XmlTextReader(caminho);


            while (x.Read())
            {
                if (x.NodeType == XmlNodeType.Element)
                {
                    switch (x.Name)
                    {
                    case "evtCPRB":
                        x.MoveToAttribute("id");
                        r2060.Id = x.Value.ToString();
                        break;

                    case "indRetif":
                        r2060.indRetif = x.ReadString();
                        break;

                    case "nrRecibo":
                        r2060.nrRecibo = x.ReadString();
                        break;

                    case "perApur":
                        r2060.perApur = DateTime.Parse(x.ReadString());
                        break;

                    case "tpAmb":
                        r2060.tpAmb = x.ReadString();
                        break;

                    case "procEmi":
                        r2060.procEmi = x.ReadString();
                        break;

                    case "verProc":
                        r2060.verProc = x.ReadString();
                        break;

                    case "tpInsc":
                        r2060.tpInsc = x.ReadString();
                        break;

                    case "nrInsc":
                        r2060.nrInsc = x.ReadString();
                        break;

                    case "tpInscEstab":
                        r2060.tpInscEstab = x.ReadString();
                        break;

                    case "nrInscEstab":
                        r2060.nrInscEstab = x.ReadString();
                        break;

                    case "vlrRecBrutaTotal":
                        r2060.vlrRecBrutaTotal = double.Parse(x.ReadString());
                        break;

                    case "vlrCPApurTotal":
                        r2060.vlrCPApurTotal = double.Parse(x.ReadString());
                        break;

                    case "vlrCPRBSuspTotal":
                        r2060.vlrCPRBSuspTotal = double.Parse(x.ReadString());
                        break;

                    //R2060infoProc
                    case "tpProc":
                        r2060InfoProc.tpProc = int.Parse(x.ReadString());
                        break;

                    case "nrProc":
                        r2060InfoProc.nrProc = x.ReadString();
                        break;

                    case "codSusp":
                        r2060InfoProc.codSusp = x.ReadString();
                        break;

                    case "vlrCPRBSusp":
                        r2060InfoProc.vlrCPRBSusp = double.Parse(x.ReadString());
                        break;

                    //R2060tipoAjuste
                    case "tpAjuste":
                        r2060TipoAjuste.tpAjuste = int.Parse(x.ReadString());
                        break;

                    case "codAjuste":
                        r2060TipoAjuste.codAjuste = int.Parse(x.ReadString());
                        break;

                    case "vlrAjuste":
                        r2060TipoAjuste.vlrAjuste = double.Parse(x.ReadString());
                        break;

                    case "descAjuste":
                        r2060TipoAjuste.descAjuste = x.ReadString();
                        break;

                    case "dtAjuste":
                        r2060TipoAjuste.dtAjuste = DateTime.Parse(x.ReadString());
                        break;

                    //R2060tipoCod
                    case "codAtivEcon":
                        r2060TipoCod.codAtivEcon = x.ReadString();
                        break;

                    case "vlrRecBrutaAtiv":
                        r2060TipoCod.vlrRecBrutaAtiv = double.Parse(x.ReadString());
                        break;

                    case "vlrExcRecBruta":
                        r2060TipoCod.vlrExcRecBruta = double.Parse(x.ReadString());
                        break;

                    case "vlrAdicRecBruta":
                        r2060TipoCod.vlrAdicRecBruta = double.Parse(x.ReadString());
                        break;

                    case "vlrBcCPRB":
                        r2060TipoCod.vlrBcCPRB = double.Parse(x.ReadString());
                        break;

                    case "vlrCPRBapur":
                        r2060TipoCod.vlrCPRBapur = double.Parse(x.ReadString());
                        break;
                    }
                }
            }

            daoR2060.Save(r2060, database, Codigo, r2060.Id);
            daoR2060InfoProc.Save(r2060InfoProc, database, Codigo, r2060.Id);
            daoR2060TipoAjuste.Save(r2060TipoAjuste, database, Codigo, r2060.Id);
            daoR2060TipoCod.Save(r2060TipoCod, database, Codigo, r2060.Id);


            return(true);
        }
Exemplo n.º 10
0
    private static void transform(XmlTextReader xin, XmlTextWriter xout,
        Dictionary<string,string> guids)
    {
        try {
          while (xin.Read()) {
        if (xin.NodeType == XmlNodeType.Element) {
          string name = xin.Name;
          bool empty = xin.IsEmptyElement;
          //Extract attributes
          KeyValuePair<string,string>[] attr =
            new KeyValuePair<string,string>[xin.HasAttributes?
                                            xin.AttributeCount : 0];
          for (int i = 0; i < attr.Length; ++i) {
            xin.MoveToAttribute(i);
            attr[i] = new KeyValuePair<string,string>(xin.Name, xin.Value);
          }

          //Perform GUID translation
          translateGUIDs(attr, guids, xin);

          //Write new node(s)
          if (name == "autowixfilecomponents")
            writeFileComponents(xout, name, attr, empty, guids, xin);
          else if (name == "autowixcomponentrefs")
            writeComponentRefs(xout, empty, xin);
          else
            writeVerbatim(xout, name, attr, empty);
        } else if (xin.NodeType == XmlNodeType.EndElement) {
          xout.WriteEndElement();
        }
          }
        } catch (XmlException e) {
          Console.WriteLine("Error reading input: " + e.Message);
          Environment.Exit(5);
        }
    }
Exemplo n.º 11
0
        private static void TryIndent(TextArea textArea, int begin, int end)
        {
            string currentIndentation = "";
            var    tagStack           = new Stack <string>();

            var    document        = textArea.Document;
            string tab             = GetIndentationString(textArea);
            int    nextLine        = begin; // in #dev coordinates
            bool   wasEmptyElement = false;
            var    lastType        = XmlNodeType.XmlDeclaration;

            using (var stringReader = new StringReader(document.Text))
            {
                var r = new XmlTextReader(stringReader);
                r.XmlResolver = null; // prevent XmlTextReader from loading external DTDs
                while (r.Read())
                {
                    if (wasEmptyElement)
                    {
                        wasEmptyElement = false;
                        if (tagStack.Count == 0)
                        {
                            currentIndentation = "";
                        }
                        else
                        {
                            currentIndentation = tagStack.Pop();
                        }
                    }
                    if (r.NodeType == XmlNodeType.EndElement)
                    {
                        // Indent lines before closing tag.
                        while (nextLine < r.LineNumber)
                        {
                            // Set indentation of 'nextLine'
                            DocumentLine line     = document.GetLineByNumber(nextLine);
                            string       lineText = document.GetText(line);

                            string newText = currentIndentation + lineText.Trim();

                            if (newText != lineText)
                            {
                                document.Replace(line.Offset, line.Length, newText);
                            }

                            nextLine += 1;
                        }

                        if (tagStack.Count == 0)
                        {
                            currentIndentation = "";
                        }
                        else
                        {
                            currentIndentation = tagStack.Pop();
                        }
                    }

                    while (r.LineNumber >= nextLine)
                    {
                        if (nextLine > end)
                        {
                            break;
                        }
                        if (lastType == XmlNodeType.CDATA || lastType == XmlNodeType.Comment)
                        {
                            nextLine++;
                            continue;
                        }
                        // set indentation of 'nextLine'
                        DocumentLine line     = document.GetLineByNumber(nextLine);
                        string       lineText = document.GetText(line);

                        string newText;
                        // special case: opening tag has closing bracket on extra line: remove one indentation level
                        if (lineText.Trim() == ">")
                        {
                            newText = tagStack.Peek() + lineText.Trim();
                        }
                        else
                        {
                            newText = currentIndentation + lineText.Trim();
                        }

                        document.SmartReplaceLine(line, newText);
                        nextLine++;
                    }

                    if (r.LineNumber >= end)
                    {
                        break;
                    }

                    wasEmptyElement = r.NodeType == XmlNodeType.Element && r.IsEmptyElement;
                    string attribIndent = null;
                    if (r.NodeType == XmlNodeType.Element)
                    {
                        tagStack.Push(currentIndentation);
                        if (r.LineNumber <= begin)
                        {
                            var whitespace = TextUtilities.GetWhitespaceAfter(document, document.GetOffset(r.LineNumber, 1));
                            currentIndentation = document.GetText(whitespace);
                        }
                        if (r.Name.Length < 16)
                        {
                            attribIndent = currentIndentation + new string(' ', 2 + r.Name.Length);
                        }
                        else
                        {
                            attribIndent = currentIndentation + tab;
                        }
                        currentIndentation += tab;
                    }

                    lastType = r.NodeType;
                    if (r.NodeType == XmlNodeType.Element && r.HasAttributes)
                    {
                        int startLine = r.LineNumber;
                        r.MoveToAttribute(0); // move to first attribute
                        if (r.LineNumber != startLine)
                        {
                            attribIndent = currentIndentation; // change to tab-indentation
                        }
                        r.MoveToAttribute(r.AttributeCount - 1);
                        while (r.LineNumber >= nextLine)
                        {
                            if (nextLine > end)
                            {
                                break;
                            }
                            // set indentation of 'nextLine'
                            DocumentLine line    = document.GetLineByNumber(nextLine);
                            string       newText = attribIndent + document.GetText(line).Trim();
                            document.SmartReplaceLine(line, newText);
                            nextLine++;
                        }
                    }
                }

                r.Close();
            }
        }
Exemplo n.º 12
0
	private void SetPropertyObject(object objParent, PropertyInfo pi, XmlTextReader tr, NodeStyle ns)
	{
		object obj;

		switch (pi.PropertyType.FullName)
			{
				case "System.Drawing.Font" :
					structFont fnt;
					fnt.Style = 0;
					fnt.Unit = GraphicsUnit.Point;
					fnt.Name="";
					fnt.Size=0;
					fnt.gdiCharSet=0;
					fnt.gdiVerticalFont=false;

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

						switch (tr.Name.ToUpper())
						{
							case "NAME" : fnt.Name = tr.Value; break;
							case "SIZE" : fnt.Size = Convert.ToSingle(tr.Value); break;
							case "GDICHARSET" : fnt.gdiCharSet = Convert.ToByte(tr.Value); break;
							case "GDIVERTICALFONT" : fnt.gdiVerticalFont = Convert.ToBoolean(tr.Value); break;
							case "BOLD" : if (Convert.ToBoolean(tr.Value)) fnt.Style = fnt.Style | FontStyle.Bold ; break;
							case "ITALIC" : if (Convert.ToBoolean(tr.Value)) fnt.Style = fnt.Style | FontStyle.Italic ; break;
							case "STRIKEOUT" : if (Convert.ToBoolean(tr.Value)) fnt.Style = fnt.Style | FontStyle.Strikeout ; break;
							case "UNDERLINE" : if (Convert.ToBoolean(tr.Value)) fnt.Style = fnt.Style | FontStyle.Underline; break;
							case "UNIT" : 
								Type o = oTV.Style.NodeStyle.Font.Unit.GetType();
								fnt.Unit = (System.Drawing.GraphicsUnit)System.Enum.Parse(o , tr.Value, true);
								break;

							default :
								break;
						}
					}

					System.Drawing.Font NewFont = new System.Drawing.Font(fnt.Name, fnt.Size, fnt.Style, fnt.Unit, fnt.gdiCharSet, fnt.gdiVerticalFont);

				Type t1 = objParent.GetType();

				switch (t1.FullName)
				{
					case "PureComponents.TreeView.NodeStyle" :						
						ns.Font = NewFont;
						break;

					case "PureComponents.TreeView.NodeTooltipStyle" :
						ns.TooltipStyle.Font = NewFont;
						break;

				}

					break;

				default :
					

					obj = (System.Type.GetType(pi.GetType().Name));
					obj = pi.GetValue(objParent,null);

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

						tr.MoveToAttribute(i);

						SetProperty(obj, tr.Name, tr.Value);

					}
					break;
			}

	}
Exemplo n.º 13
0
	private Node LoadNode(string sXML)
	{
		Node ReturnedNode = null;

		if (sXML.Length == 0) return ReturnedNode;

		ReturnedNode = new Node();
		ReturnedNode.TreeView = oTV;

		XmlTextReader tr = new XmlTextReader(sXML, System.Xml.XmlNodeType.Element , null);		

		while (tr.Read())
			if (tr.IsStartElement()) break;

		//nastavi atributy nodu
		for (int i = 0; i < tr.AttributeCount; i++)
		{

			tr.MoveToAttribute(i);

			SetProperty(ReturnedNode, tr.Name, tr.Value);

		}

		bool NextElement = true;


		while (NextElement)
		{
			while (tr.Read())
				if (tr.IsStartElement()) break;

			string ElementName = tr.LocalName;

			if (ElementName.Length == 0) break;

			switch (ElementName.ToUpper())
			{
				case "TEXT" :
					string s = this.LoadMultiLineText(tr.ReadString());
					
					SetProperty(ReturnedNode, "Text", s);

					break;

				case "FLAG" :
					for (int i = 0; i < tr.AttributeCount; i++)
					{
						tr.MoveToAttribute(i);

						SetProperty(ReturnedNode.Flag, tr.Name, tr.Value);
					}
					break;

				case "NODESTYLE" :
					this.LoadObject(ReturnedNode, tr.ReadOuterXml(), ReturnedNode.NodeStyle);
					break;

				case "NODE" :				
					Node n = LoadNode(tr.ReadOuterXml());					
					if (n != null)
					{
						ReturnedNode.Nodes.Add(n);
						//n.Parent = ReturnedNode;
						//n.TreeView = ReturnedNode.TreeView;
					}
					break;

			}
		}

		return ReturnedNode;
	}
Exemplo n.º 14
0
	private void LoadNodes(object objParent, string sXML)
	{
		if (sXML.Length == 0) return;

		XmlTextReader tr = new XmlTextReader(sXML, System.Xml.XmlNodeType.Element , null);

		while (tr.ReadState != ReadState.EndOfFile)
		{

			while (tr.Read())
				if (tr.IsStartElement()) break;

			string ElementName = tr.LocalName;

			if (ElementName.Length == 0) break;

			switch (ElementName.ToUpper())
			{
				case "BEHAVIOR" :

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

						tr.MoveToAttribute(i);						

						SetProperty(oTV, tr.Name, tr.Value);

					}
					
					break;

				case "NODE" :

					while (tr.ReadState != ReadState.EndOfFile)
					{
						if (tr.LocalName.ToUpper() == "NODE")
						{
							Node n = null;

							string s = tr.ReadOuterXml();

							if (s.Length > 0)
							{
								n = LoadNode(s);
					
								if (n != null) oTV.Nodes.Add(n);
							}
						}
						else tr.Read();
					}

					break;
			}

		}
	}
Exemplo n.º 15
0
        public static Configuration Read()
        {
            Configuration conf   = new Configuration();
            XmlTextReader reader = new XmlTextReader(ConfigFile);

            string[] Attributes    = null;
            string[] Value         = null;
            bool     isListContent = false;

            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                case XmlNodeType.Element:
                    if (reader.AttributeCount > 0)
                    {
                        Attributes = new string[reader.AttributeCount];
                        Value      = new string[reader.AttributeCount];

                        for (int i = 0; i < reader.AttributeCount; i++)
                        {
                            reader.MoveToAttribute(i);
                            Attributes[i] = reader.Name;
                            Value[i]      = reader.Value;
                        }
                        if (reader.AttributeCount > 0)
                        {
                            for (int i = 0; i < Attributes.Length; i++)
                            {
                                if (Attributes[i].ToUpper() == "NAME")
                                {     //ModifyListContent/Sharepoint/List/Name
                                    conf.SharepointLists.Add(new SharepointList(Value[i]));
                                    isListContent = false;
                                }
                            }
                        }
                    }
                    else
                    {
                        if (reader.Name.ToUpper() == "URL")
                        {     //ModifyListContent/Sharepoint/General/Url
                            conf.Urls.Add(reader.ReadString());
                            isListContent = false;
                        }
                        else if (reader.Name.ToUpper() == "COLNAME")
                        {     //ModifyListContent/Sharepoint/List/Columns
                            conf.SharepointLists.Last <SharepointList>().Columns.Add(reader.ReadString());
                            isListContent = false;
                        }
                        else if (reader.Name.ToUpper() == "CONTENTS")
                        {     //ModifyListContent/Sharepoint/List/Content
                            isListContent = true;
                        }
                        else
                        {
                            if (isListContent)
                            {
                                foreach (string col in conf.SharepointLists.Last <SharepointList>().Columns)
                                {
                                    if (reader.Name.ToUpper() == col.ToUpper().Replace(" ", "_"))
                                    {
                                        conf.SharepointLists.Last <SharepointList>().Content.Add(new KeyValuePair <string, string>(col, reader.ReadString()));
                                    }
                                }
                            }
                        }
                    }
                    break;
                }
            }
            reader.Close();
            //**************************************************
            return(conf);
        }
Exemplo n.º 16
0
        /// <summary>
        /// parses the datum from the esri string
        /// </summary>
        /// <param name="esriString">The string to parse values from</param>
        public void ParseEsriString(string esriString)
        {
            if (System.String.IsNullOrEmpty(esriString))
            {
                return;
            }

            if (esriString.Contains("DATUM") == false)
            {
                return;
            }
            int iStart = esriString.IndexOf("DATUM") + 7;
            int iEnd   = esriString.IndexOf(@""",", iStart) - 1;

            if (iEnd < iStart)
            {
                return;
            }
            _name = esriString.Substring(iStart, iEnd - iStart + 1);

            Assembly currentAssembly         = Assembly.GetExecutingAssembly();
            string   fileName                = null;
            string   currentAssemblyLocation = currentAssembly.Location;

            if (!String.IsNullOrEmpty(currentAssemblyLocation))
            {
                fileName = Path.GetDirectoryName(currentAssemblyLocation) + "\\datums.xml";
            }
            Stream datumStream = File.Exists(fileName) ? File.Open(fileName, FileMode.Open) : currentAssembly.GetManifestResourceStream("DotSpatial.Projections.XML.datums.xml");

            if (datumStream != null)
            {
                XmlTextReader reader = new XmlTextReader(datumStream);

                while (reader.Read())
                {
                    if (reader.AttributeCount == 0)
                    {
                        continue;
                    }
                    reader.MoveToAttribute("Name");
                    if (reader.Value != _name)
                    {
                        continue;
                    }
                    reader.MoveToAttribute("Type");
                    if (string.IsNullOrEmpty(reader.Value))
                    {
                        break;
                    }
                    DatumType = (DatumType)Enum.Parse(typeof(DatumType), reader.Value);
                    switch (DatumType)
                    {
                    case DatumType.Param3:
                    {
                        double[] transform = new double[3];
                        for (int i = 0; i < 3; i++)
                        {
                            reader.MoveToAttribute("P" + (i + 1));
                            if (!string.IsNullOrEmpty(reader.Value))
                            {
                                transform[i] = double.Parse(reader.Value, CultureInfo.InvariantCulture);
                            }
                        }
                        ToWGS84 = transform;
                    }
                    break;

                    case DatumType.Param7:
                    {
                        double[] transform = new double[7];
                        for (int i = 0; i < 7; i++)
                        {
                            reader.MoveToAttribute("P" + (i + 1));
                            if (!string.IsNullOrEmpty(reader.Value))
                            {
                                transform[i] = double.Parse(reader.Value, CultureInfo.InvariantCulture);
                            }
                        }
                        ToWGS84 = transform;
                        break;
                    }

                    case DatumType.GridShift:
                        reader.MoveToAttribute("Shift");
                        if (string.IsNullOrEmpty(reader.Value))
                        {
                            continue;
                        }
                        NadGrids = reader.Value.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                        break;
                    }
                    break;
                }
            }

            _spheroid.ParseEsriString(esriString);
        }
Exemplo n.º 17
0
        private void ProcessElement(XmlTextReader inFile, XmlTextWriter xmlOutput)
        {
            string saveGuid = "";

            if (holdNode == "CustomField" || holdNode == "AdditionalFields")
            {
                return;
            }

            else if (holdNode == "FwDatabase")                          // write the root element
            {
                xmlOutput.WriteStartElement("languageproject");
                WriteXMLAttribute("version", holdVersion, xmlOutput);

                if (holdVersion == null)
                {
                    throw new Exception("The version attribute was not found in the root node of the model file " + m_ModelName);
                }
                // Make an initial pass to process the Custom Fields
                // Flag will be false if there aren't any.
                if (ProcessCustomFields() == true)
                {
                    WriteCustomHeaders(xmlOutput);
                }
            }

            else if (inFile.GetAttribute("id") != null)                         // write an rt element
            {
                if (stackElements.Count > 0)
                {
                    if (stackClasses.Count == 0)
                    {
                        currentRT = langProjClass;
                    }

                    PopPastSubentries();
                    inFile.MoveToAttribute("id");
                    //inFile.Value; // "I983B657C-9F1E-4A96-999A-CE200EA01302")
                    if (stackElements.Count > 0 && currentRT.elementList.TryGetValue(int.Parse(GetElementNumber(stackElements.Peek())), out elemDEntry) != true)
                    {
                        elemDEntry = new StringCollection();
                        currentRT.elementList.Add(int.Parse(GetElementNumber(stackElements.Peek())), elemDEntry);
                    }
                    elemDEntry.Add("<objsur t=\"o\" guid=\"" + inFile.Value.Substring(1) + "\"/>");
                }
                CreateRtElement(inFile, xmlOutput);
            }

            else if (holdNode == "Link")                        // write a link element
            {
                inFile.MoveToAttribute("target");
                saveGuid = inFile.Value.Substring(1);
                PopPastSubentries();
                if (currentRT.elementList.TryGetValue(int.Parse(GetElementNumber(stackElements.Peek())), out elemDEntry) != true)
                {
                    elemDEntry = new StringCollection();
                    currentRT.elementList.Add(int.Parse(GetElementNumber(stackElements.Peek())), elemDEntry);
                }
                elemDEntry.Add("<objsur t=\"r\" guid=\"" + saveGuid + "\"/>");
            }
            else if (holdNode == "Run" && inFile.GetAttribute("ws") == null)      // Make sure runs have WS
            {
                WriteElement(inFile, xmlOutput, "", "ws=\"en\"");                 // write the element, guessing it should be English
            }

            else if (stackClasses.Count > 0 && holdNode.Length >= 6 && holdNode.Substring(0, 6) == "Custom") // write a custom data element
            {
                WriteElement(inFile, xmlOutput, GetNewCustomName(inFile), "");                               // write the next element in the class
            }

            else                                                                        // Class Sub-element
            {
                WriteElement(inFile, xmlOutput, "", "");                                // write the next element in the class
            }
        }
Exemplo n.º 18
0
        public void Parse(string filePath)
        {
            try
            {
            XmlTextReader reader = new XmlTextReader(filePath);
            reader.WhitespaceHandling = WhitespaceHandling.None;
            while (reader.Read())
            {
                if (this.inMathNode == true)
                {
                    ParseMath(reader);
                    continue;
                }

                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        if (reader.Prefix != String.Empty)
                        {
                            // namespaced element not part of SBML
                            reader.Skip();
                        }
                        String elementName = reader.LocalName.ToLower();

                        if (elementName == "notes" ||
                            elementName == "annotation")
                        {
                            // not part of the SBML model
                            //reader.Skip(); // need to skip then move back one node
                            reader.Read();
                        }

                        Hashtable attributes = new Hashtable();
                        if (reader.HasAttributes)
                        {
                            for (int i = 0; i < reader.AttributeCount; i++)
                            {
                                reader.MoveToAttribute(i);
                                if (reader.Name == "xmlns" && elementName != "math"
                                    && elementName != "sbml")
                                {
                                    // namespaced node/subtree not part of SBML...unless MathML
                                    reader.MoveToElement();
                                    reader.Skip();
                                }
                                if (reader.Name == "specie")
                                {
                                    // horrible leftover from SBML Level 1
                                    attributes.Add("species", reader.Value);
                                }
                                else
                                {
                                    attributes.Add(reader.Name.ToLower(), reader.Value);
                                }
                            }
                        }
                        StartElement(elementName, attributes);
                        break;

                    case XmlNodeType.EndElement:
                        EndElement(reader.LocalName.ToLower());
                        break;
                    // There are many other types of nodes, but
                    // we are not interested in them
                }
            }
            }
            catch (XmlException e)
            {
            Console.WriteLine(e.Message);
            }
        }
        private void DeserializeTreeView(string fileName)
        {
            XmlTextReader reader = null;

            try
            {
                reader = new XmlTextReader(fileName);
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        //for load from explorer
                        if (reader.Name == "Node")
                        {
                            reader.MoveToAttribute("Node");
                            foreach (TreeViewItem dataNo in foldersItem.Items)
                            {
                                if (dataNo.Header.ToString() == reader.Value)
                                {
                                    dataNo.IsExpanded = true;
                                }

                                if (dataNo.IsExpanded)
                                {
                                    TreeRunnerLoad(reader.Value, dataNo);
                                }
                            }
                        }
                        // for load from explorer
                        if (reader.Name == "SelectedImagePath")
                        {
                            reader.MoveToAttribute("SelectedImagePath");

                            SelectedImagePath = reader.Value;
                            DirExplorerViewModel.ChangeDirEvent(SelectedImagePath);
                        }
                        // for load from DB
                        if (reader.Name == "Category")
                        {
                            DbTree.IsSelected = true;
                            reader.MoveToAttribute("Category");
                            DirExplorerViewModel.SelectedinDbChanged(reader.Value);
                            _currentCategoryInDb = reader.Value;
                        }
                    }
                    else if (reader.NodeType == XmlNodeType.XmlDeclaration)
                    {
                        //Ignore Xml Declaration
                    }
                    else if (reader.NodeType == XmlNodeType.None)
                    {
                        return;
                    }
                }
            }

            catch (Exception)
            {
                // ignored
            }
            finally
            {
                reader.Close();
            }
        }
Exemplo n.º 20
0
        private DataTable Read_Item_Xml(string fileName)
        {
            // Create the datatable to hold this data and define each column
            DataTable  importItemsTable = new DataTable("Items");
            DataColumn titleIdColumn    = importItemsTable.Columns.Add("TItle_ID");
            DataColumn itemIdColumn     = importItemsTable.Columns.Add("Item_ID");
            DataColumn titleColumn      = importItemsTable.Columns.Add("Title");
            DataColumn dateColumn       = importItemsTable.Columns.Add("Date");
            DataColumn urlColumn        = importItemsTable.Columns.Add("URL");
            DataColumn webColumn        = importItemsTable.Columns.Add("Web_Folder");
            DataColumn networkColumn    = importItemsTable.Columns.Add("Network_Folder");

            // Create the temporary values here
            string titleId = String.Empty;
            string itemId  = String.Empty;
            string title   = String.Empty;
            string date    = String.Empty;
            string url     = String.Empty;
            string web     = String.Empty;
            string network = String.Empty;

            // Open a connection to the XML file and step through the XML
            XmlTextReader reader = new XmlTextReader(new StreamReader(fileName));

            while (reader.Read())
            {
                // What type of XML node is this?
                if (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.Name)
                    {
                    case "ItemResult":
                        if (reader.MoveToAttribute("ID"))
                        {
                            itemId = reader.Value;
                        }
                        break;

                    case "Title":
                        reader.Read();
                        title = reader.Value;
                        break;

                    case "Date":
                        reader.Read();
                        date = reader.Value;
                        break;

                    case "URL":
                        reader.Read();
                        url = reader.Value;
                        break;

                    case "Folder":
                        if (reader.MoveToAttribute("type"))
                        {
                            if (reader.Value == "web")
                            {
                                reader.Read();
                                web = reader.Value;
                            }
                            else if (reader.Value == "network")
                            {
                                reader.Read();
                                network = reader.Value;
                            }
                        }
                        break;

                    case "TitleResult":
                        if (reader.MoveToAttribute("ID"))
                        {
                            titleId = reader.Value;
                        }
                        break;
                    }
                }
                else if (reader.NodeType == XmlNodeType.EndElement)
                {
                    // Is this ending the title or an item within the title?
                    switch (reader.Name)
                    {
                    case "ItemResult":
                        // Create the new row and assign all the values
                        DataRow newRow = importItemsTable.NewRow();
                        newRow[titleIdColumn] = titleId;
                        newRow[itemIdColumn]  = itemId;
                        newRow[titleColumn]   = title;
                        newRow[dateColumn]    = date;
                        newRow[urlColumn]     = url;
                        newRow[webColumn]     = web;
                        newRow[networkColumn] = network;
                        importItemsTable.Rows.Add(newRow);

                        // Now, clear out all the item-level data
                        itemId  = String.Empty;
                        title   = String.Empty;
                        date    = String.Empty;
                        url     = String.Empty;
                        web     = String.Empty;
                        network = String.Empty;
                        break;


                    case "TitleResult":
                        // Clear out the last title bit of information
                        titleId = String.Empty;
                        break;
                    }
                }
            }
            reader.Close();

            return(importItemsTable);
        }
Exemplo n.º 21
0
        //-------------------------------------------------------------------------
        // NG USER ID読み込み
        //-------------------------------------------------------------------------
        public void LoadNGUserID(bool iAnon)
        {
            string file = (iAnon) ? "ng_anonymous.xml" : "ng_userid.xml";

            using (XmlTextReader xml = new XmlTextReader(file))
            {
                if (xml == null)
                {
                    Utils.WriteLog(file + "が見つかりません");
                    return;
                }

                string id = "";

                try
                {
                    while (xml.Read())
                    {
                        if (xml.NodeType == XmlNodeType.Element)
                        {
                            // 古いXMLファイルは削除
                            if (iAnon)
                            {
                                if (xml.LocalName.Equals("date"))
                                {
                                    string d      = xml.ReadString();
                                    long   create = long.Parse(d);

                                    TimeSpan ts = new TimeSpan(DateTime.Now.Ticks - create);

                                    // 七日以上経過は削除
                                    if (ts.Days > 7)
                                    {
                                        return;
                                    }

                                    // 木曜11時以降は作成日が木曜じゃない設定は削除
                                    DayOfWeek week = DateTime.Now.DayOfWeek;
                                    if (week == DayOfWeek.Thursday && DateTime.Now.Hour >= 11)
                                    {
                                        DateTime  dt = new DateTime(create);
                                        DayOfWeek w  = dt.DayOfWeek;
                                        if (w != DayOfWeek.Thursday || (w == DayOfWeek.Thursday && dt.Hour < 11))
                                        {
                                            Utils.WriteLog("REFRESH ID");
                                            return;
                                        }
                                    }
                                }
                            }


                            if (xml.LocalName.Equals("user"))
                            {
                                for (int i = 0; i < xml.AttributeCount; i++)
                                {
                                    xml.MoveToAttribute(i);
                                    if (xml.Name == "id")
                                    {
                                        id = xml.Value;
                                    }
                                }

                                mNGUserList.Add(id);
                                Utils.WriteLog("read ng user:  id:" + id);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Utils.WriteLog("LoadNGUser:" + e.Message);
                }
            }
        }
Exemplo n.º 22
0
        public void Load(string fileName)
        {
            ModelClass     classEntry;
            ReferenceField childEntry;
            EnumField      enumEntry;

            FileInfo file = new FileInfo(fileName);

            // Progress Start Event
            this.OnProgressStart(this, new DataModelEventArgs(
                                     string.Format(Properties.Resources.ProgressBarLoadText, name),
                                     string.Empty,
                                     "LOAD", new ProgressBarConfig(0, 5, 0, 1)));

            //
            // Test for file existence.
            //
            if (!File.Exists(fileName))
            {
                // Try Loading the NitroCast File
                fileName = fileName.Replace(".DbModel", ".NitroGen");

                if (!File.Exists(fileName))
                {
                    this.OnProgressStop(this, new DataModelEventArgs(
                                            string.Format(Properties.Resources.ProgressBarLoadFailed, file.Name),
                                            string.Empty, "LOAD"));
                    throw new System.IO.FileNotFoundException(
                              string.Format(Properties.Resources.ProgressBarLoadFailed, file.Name));
                }
            }

            this.OnProgressUpdate(this, new DataModelEventArgs(
                                      string.Format(Properties.Resources.ProgressBarLoadInitialize, file.Name),
                                      string.Empty, "LOAD"));

            #region Clear References and Classes

            references.Clear();
            folders.Clear();

            #endregion

            this.OnProgressUpdate(this, new DataModelEventArgs(
                                      string.Format(Properties.Resources.ProgressBarLoadParse, file.Name),
                                      string.Empty, "LOAD"));

            #region Parse Model

            this.fileName = fileName;

            XmlTextReader r = new XmlTextReader(fileName);
            r.WhitespaceHandling = WhitespaceHandling.None;

            r.MoveToContent();

            if (!(r.Name == "dbModel" | r.Name == "NitroCast"))
            {
                throw new Exception("Source file does not match NitroCast DTD.");
            }

            r.MoveToAttribute("version");
            string version = r.Value;
            r.MoveToContent();

            switch (version)
            {
//				case "1.0":
//					r.Read();
//					parse1_0File(r);
//					break;
//				case "1.1":
//					r.Read();
//					parse1_1File(r);
//					break;
            case "1.11":
                r.Read();
                parse1_11File(r);
                break;

            default:
                r.Close();
                throw new Exception(string.Format("Source file version '{0}' incompatible.", version));
            }
            r.Close();

            #endregion

            this.OnProgressUpdate(this, new DataModelEventArgs(
                                      string.Format(Properties.Resources.ProgressBarLoadReferences, file.Name),
                                      string.Empty, "LOAD"));

            #region Load Referenced Data Types

            //
            // Create DataTypes For References Class Entries
            //
            foreach (ReferenceEntry reference in references)
            {
                DataModel m = new DataModel();

                m.Load(PathConverter.GetAbsolutePath(file.DirectoryName, reference.FileName));
                reference.Name = m.Name;

                foreach (ModelFolder folder in m.Folders)
                {
                    foreach (object item in folder.Items)
                    {
                        if (item is ModelClass)
                        {
                            DataTypeManager.AddDataType(new ReferenceType((ModelClass)item, reference));
                        }
                        else if (item is ModelEnum)
                        {
                            DataTypeManager.AddDataType(new EnumType((ModelEnum)item, reference));
                        }
                    }
                }
            }

            #endregion

            this.OnProgressUpdate(this, new DataModelEventArgs(
                                      string.Format(Properties.Resources.ProgressBarLoadBuild, file.Name),
                                      string.Empty, "LOAD"));

            #region Load Internal Data Types

            foreach (ModelFolder f in folders)
            {
                foreach (object item in f.Items)
                {
                    if (item is ModelClass)
                    {
                        DataTypeManager.AddDataType(new ReferenceType((ModelClass)item, null));
                    }
                    else if (item is ModelEnum)
                    {
                        DataTypeManager.AddDataType(new EnumType((ModelEnum)item, null));
                    }
                }
            }

            #endregion

            this.OnProgressUpdate(this, new DataModelEventArgs(
                                      string.Format(Properties.Resources.ProgressBarLoadSort, file.Name),
                                      string.Empty, "LOAD"));

            DataTypeManager.ReferenceTypes.Sort(ModelEntryCompareKey.Name);
            DataTypeManager.ValueTypes.Sort(ModelEntryCompareKey.Name);
            DataTypeManager.EnumTypes.Sort(ModelEntryCompareKey.Name);

            this.OnProgressUpdate(this, new DataModelEventArgs(
                                      string.Format(Properties.Resources.ProgressBarLoadAssociate, file.Name),
                                      string.Empty, "LOAD"));

            #region Associate Datatypes to Children

            //
            // Associate DataTypes to class children.
            //
            foreach (ModelFolder folder in folders)
            {
                foreach (object item in folder.Items)
                {
                    if (item is ModelClass)
                    {
                        classEntry = (ModelClass)item;

                        foreach (ClassFolder classFolder in classEntry.Folders)
                        {
                            foreach (object folderItem in classFolder.Items)
                            {
                                if (folderItem is ReferenceField)
                                {
                                    childEntry = (ReferenceField)folderItem;

                                    if (childEntry.ReferenceType.IsCustom)
                                    {
                                        foreach (ReferenceType cType in DataTypeManager.ReferenceTypes)
                                        {
                                            if (childEntry.ReferenceType.Name == cType.Name &
                                                childEntry.ReferenceType.NameSpace == cType.NameSpace)
                                            {
                                                childEntry.ReferenceType = cType;
                                            }
                                        }
                                    }
                                }
                                else if (folderItem is EnumField)
                                {
                                    enumEntry = (EnumField)folderItem;

                                    if (enumEntry.EnumType.IsCustom)
                                    {
                                        foreach (EnumType cType in DataTypeManager.EnumTypes)
                                        {
                                            if (enumEntry.EnumType.Name == cType.Name &
                                                enumEntry.EnumType.NameSpace == cType.NameSpace)
                                            {
                                                enumEntry.EnumType = cType;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            #endregion

            this.OnProgressStop(this, new DataModelEventArgs(string.Empty, string.Empty, "LOAD"));
        }
Exemplo n.º 23
0
        //-------------------------------------------------------------------------
        // USER ID読み込み
        //-------------------------------------------------------------------------
        public void LoadUserID(bool iAnon)
        {
            string file = (iAnon) ? "anonymous.xml" : "userid.xml";

            using (XmlTextReader xml = new XmlTextReader(file))
            {
                if (xml == null)
                {
                    Utils.WriteLog(file + "が見つかりません");
                    return;
                }


                string id              = "";
                string nick            = "";
                System.Drawing.Color c = System.Drawing.Color.White;
                string color           = String.Format("{0:x2}", c.A) + String.Format("{0:x2}", c.R) + String.Format("{0:x2}", c.G) + String.Format("{0:x2}", c.B);


                try
                {
                    while (xml.Read())
                    {
                        if (xml.NodeType == XmlNodeType.Element)
                        {
                            // 古いXMLファイルは削除
                            if (iAnon)
                            {
                                if (xml.LocalName.Equals("date"))
                                {
                                    string d      = xml.ReadString();
                                    long   create = long.Parse(d);

                                    TimeSpan ts = new TimeSpan(DateTime.Now.Ticks - create);

                                    // 七日以上経過は削除
                                    if (ts.Days > 7)
                                    {
                                        return;
                                    }

                                    // 木曜11時以降は作成日が木曜じゃない設定は削除
                                    DayOfWeek week = DateTime.Now.DayOfWeek;
                                    if (week == DayOfWeek.Thursday && DateTime.Now.Hour >= 11)
                                    {
                                        DateTime  dt = new DateTime(create);
                                        DayOfWeek w  = dt.DayOfWeek;
                                        if (w != DayOfWeek.Thursday || (w == DayOfWeek.Thursday && dt.Hour < 11))
                                        {
                                            Utils.WriteLog("REFRESH ID");
                                            return;
                                        }
                                    }
                                }
                            }

                            if (xml.LocalName.Equals("user"))
                            {
                                for (int i = 0; i < xml.AttributeCount; i++)
                                {
                                    xml.MoveToAttribute(i);
                                    if (xml.Name == "id")
                                    {
                                        id = xml.Value;
                                    }
                                    else if (xml.Name == "color")
                                    {
                                        color = xml.Value;
                                    }
                                }
                                nick = xml.ReadString();
                                string a = color.Substring(0, 2);
                                string r = color.Substring(2, 2);
                                string g = color.Substring(4, 2);
                                string b = color.Substring(6, 2);

                                mNickHash[id]  = nick;
                                mColorHash[id] = System.Drawing.Color.FromArgb(Convert.ToInt32(a, 16), Convert.ToInt32(r, 16), Convert.ToInt32(b, 16), Convert.ToInt32(b, 16));
                                //Utils.WriteLog(id + "   " + nick);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Utils.WriteLog("LoadUser:" + e.Message);
                }
            }
        }
Exemplo n.º 24
0
        bool ReadXMLString(ref clsXMLUpdate.clsXMLItem item, string xmlString)
        {
            bool flag;

            try
            {
                XmlTextReader xmlTextReader = new XmlTextReader((TextReader) new StringReader(xmlString));
                if (xmlTextReader.IsStartElement("Planner"))
                {
                    xmlTextReader.MoveToAttribute("Version");
                    if (xmlTextReader.ReadAttributeValue())
                    {
                        Conversion.Val(xmlTextReader.Value);
                    }
                }
                int num = 0;
                do
                {
                    xmlTextReader.Read();
                    if (xmlTextReader.Name != item.NodeName)
                    {
                        ++num;
                    }
                    else
                    {
                        break;
                    }
                }while (num <= 50);
                xmlTextReader.ReadStartElement(item.NodeName);
                xmlTextReader.ReadStartElement("Name");
                item.DisplayName = xmlTextReader.ReadString();
                xmlTextReader.ReadEndElement();
                xmlTextReader.ReadStartElement("URI");
                item.SourceURI = xmlTextReader.ReadString();
                xmlTextReader.ReadEndElement();
                xmlTextReader.ReadStartElement("LocalDest");
                item.LocalDest = FileIO.AddSlash(MyProject.Application.Info.DirectoryPath) + xmlTextReader.ReadString();
                xmlTextReader.ReadEndElement();
                xmlTextReader.ReadStartElement("Size");
                item.Size = (int)Math.Round(Conversion.Val(xmlTextReader.ReadString().Replace(",", "").Replace(".", "")));
                xmlTextReader.ReadEndElement();
                xmlTextReader.ReadStartElement("Version");
                item.Version = (float)Conversion.Val(xmlTextReader.ReadString());
                xmlTextReader.ReadEndElement();
                xmlTextReader.ReadStartElement("Date");
                string[] strArray = xmlTextReader.ReadString().Split("/".ToCharArray());
                if (strArray[2].Length == 2)
                {
                    strArray[2] = "20" + strArray[2];
                }
                item.VersionDate = new DateTime(Conversions.ToInteger(strArray[2]), Conversions.ToInteger(strArray[1]), Conversions.ToInteger(strArray[0]));
                xmlTextReader.ReadEndElement();
                xmlTextReader.ReadStartElement("Restart");
                string str1 = xmlTextReader.ReadString();
                item.Restart = str1 == "YES" | str1 == "1";
                xmlTextReader.ReadEndElement();
                xmlTextReader.ReadStartElement("Manual");
                string str2 = xmlTextReader.ReadString();
                item.Manual = str2 == "YES" | str2 == "1";
                xmlTextReader.ReadEndElement();
                xmlTextReader.ReadStartElement("Notes");
                item.Notes = xmlTextReader.ReadString().Replace("^", "\r\n");
                xmlTextReader.ReadEndElement();
                xmlTextReader.ReadEndElement();
                xmlTextReader.Close();
                flag = true;
            }
            catch (Exception ex)
            {
                ProjectData.SetProjectError(ex);
                flag = false;
                ProjectData.ClearProjectError();
            }
            return(flag);
        }
Exemplo n.º 25
0
        public override PersonalizationState LoadPersonalizationState(WebPartManager webPartManager, bool ignoreCurrentUser)
        {
            if (null == webPartManager)
            {
                throw new ArgumentNullException("webPartManager is null");
            }
            DictionaryPersonalizationState state = new DictionaryPersonalizationState(webPartManager);
            string suid = this.GetScreenUniqueIdentifier();

            Cache cache = HttpRuntime.Cache;

            lock (SyncRoot)
            {
                Dictionary <string, PersonalizationDictionary> cachedstates = cache[suid] as Dictionary <string, PersonalizationDictionary>;
                if ((this.IsEnabled && !state.ReadOnly) || null == cachedstates)
                {
                    string storage = PersonalizationStorage.Instance.Read(XmlPersonalizationProvider.StorageKey, XmlPersonalizationProvider.StorageTemplate);
                    if (!string.IsNullOrEmpty(storage))
                    {
                        using (XmlTextReader reader = new XmlTextReader(new StringReader(storage)))
                        {
                            reader.MoveToContent();
                            if (reader.MoveToAttribute("readOnly"))
                            {
                                bool isReadOnly = false;
                                bool.TryParse(reader.Value, out isReadOnly);
                                state.ReadOnly = isReadOnly;
                                reader.MoveToElement();
                            }
                            if (reader.ReadToDescendant("part"))
                            {
                                int partDepth = reader.Depth;
                                do
                                {
                                    reader.MoveToElement();
                                    reader.MoveToAttribute("id");
                                    string id = reader.Value;
                                    PersonalizationDictionary dictionary = new PersonalizationDictionary();
                                    reader.MoveToContent();
                                    if (reader.ReadToDescendant("property"))
                                    {
                                        int propertyDepth = reader.Depth;
                                        do
                                        {
                                            reader.MoveToElement();
                                            reader.MoveToAttribute("name");
                                            string name = reader.Value;
                                            reader.MoveToAttribute("sensitive");
                                            bool sensitive = bool.Parse(reader.Value);
                                            reader.MoveToAttribute("scope");
                                            PersonalizationScope scope = (PersonalizationScope)int.Parse(reader.Value);
                                            object value = null;
                                            reader.MoveToContent();
                                            if (reader.ReadToDescendant("value"))
                                            {
                                                reader.MoveToAttribute("type");
                                                if (reader.HasValue)
                                                {
                                                    Type type = Type.GetType(reader.Value);
                                                    if (type == null && name == "Configuration")
                                                    {
                                                        type = Type.GetType("LWAS.Infrastructure.Configuration.Configuration, LWAS");
                                                    }
                                                    reader.MoveToContent();
                                                    value = SerializationServices.Deserialize(type, reader);
                                                }
                                            }
                                            dictionary.Add(name, new PersonalizationEntry(value, scope, sensitive));
                                            reader.MoveToElement();
                                            while (propertyDepth < reader.Depth && reader.Read())
                                            {
                                            }
                                        }while (reader.ReadToNextSibling("property"));
                                    }
                                    state.States.Add(id, dictionary);
                                    reader.MoveToElement();
                                    while (partDepth < reader.Depth && reader.Read())
                                    {
                                    }
                                }while (reader.ReadToNextSibling("part"));
                            }
                        }
                    }

                    string fileToMonitor = PersonalizationStorage.Instance.BuildPath(StorageKey);
                    if (!PersonalizationStorage.Instance.Agent.HasKey(fileToMonitor))
                    {
                        fileToMonitor = PersonalizationStorage.Instance.BuildPath(StorageTemplate);
                    }
                    cache.Insert(suid, state.States, new CacheDependency(HttpContext.Current.Server.MapPath(fileToMonitor)));
                }
                else
                {
                    state.States = cachedstates;
                }
            }

            return(state);
        }
Exemplo n.º 26
0
 protected override bool EvaluateXmlElement(XmlTextReader xml)
 {
     return(!xml.MoveToAttribute("redirect"));
 }
Exemplo n.º 27
0
        /// <summary>Reads the next RssElement from the stream.</summary>
        /// <returns>An RSS Element</returns>
        /// <exception cref="InvalidOperationException">RssReader has been closed, and can not be read.</exception>
        /// <exception cref="System.IO.FileNotFoundException">RSS file not found.</exception>
        /// <exception cref="System.Xml.XmlException">Invalid XML syntax in RSS file.</exception>
        /// <exception cref="System.IO.EndOfStreamException">Unable to read an RssElement. Reached the end of the stream.</exception>
        public RssElement Read()
        {
            bool       readData     = false;
            bool       pushElement  = true;
            RssElement rssElement   = null;
            int        lineNumber   = -1;
            int        linePosition = -1;

            if (reader == null)
            {
                throw new InvalidOperationException("RssReader has been closed, and can not be read.");
            }

            do
            {
                pushElement = true;
                try
                {
                    readData = reader.Read();
                }
                catch (System.IO.EndOfStreamException e)
                {
                    throw new System.IO.EndOfStreamException("Unable to read an RssElement. Reached the end of the stream.", e);
                }
                catch (System.Xml.XmlException e)
                {
                    if (lineNumber != -1 || linePosition != -1)
                    {
                        if (reader.LineNumber == lineNumber && reader.LinePosition == linePosition)
                        {
                            throw exceptions.LastException;
                        }
                    }

                    lineNumber   = reader.LineNumber;
                    linePosition = reader.LinePosition;

                    exceptions.Add(e);                     // just add to list of exceptions and continue :)
                }
                if (readData)
                {
                    string readerName = reader.Name.ToLower();
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.Element:
                    {
                        if (reader.IsEmptyElement)
                        {
                            break;
                        }
                        elementText = new StringBuilder();

                        switch (readerName)
                        {
                        case "item":
                            // is this the end of the channel element? (absence of </channel> before <item>)
                            if (!wroteChannel)
                            {
                                wroteChannel = true;
                                rssElement   = channel;                                               // return RssChannel
                                readData     = false;
                            }
                            item = new RssItem();                                             // create new RssItem
                            channel.Items.Add(item);
                            break;

                        case "source":
                            source      = new RssSource();
                            item.Source = source;
                            for (int i = 0; i < reader.AttributeCount; i++)
                            {
                                reader.MoveToAttribute(i);
                                switch (reader.Name.ToLower())
                                {
                                case "url":
                                    try
                                    {
                                        source.Url = new Uri(reader.Value);
                                    }
                                    catch (Exception e)
                                    {
                                        exceptions.Add(e);
                                    }
                                    break;
                                }
                            }
                            break;

                        case "enclosure":
                            enclosure      = new RssEnclosure();
                            item.Enclosure = enclosure;
                            for (int i = 0; i < reader.AttributeCount; i++)
                            {
                                reader.MoveToAttribute(i);
                                switch (reader.Name.ToLower())
                                {
                                case "url":
                                    try
                                    {
                                        enclosure.Url = new Uri(reader.Value);
                                    }
                                    catch (Exception e)
                                    {
                                        exceptions.Add(e);
                                    }
                                    break;

                                case "length":
                                    try
                                    {
                                        enclosure.Length = int.Parse(reader.Value);
                                    }
                                    catch (Exception e)
                                    {
                                        exceptions.Add(e);
                                    }
                                    break;

                                case "type":
                                    enclosure.Type = reader.Value;
                                    break;
                                }
                            }
                            break;

                        case "guid":
                            guid      = new RssGuid();
                            item.Guid = guid;
                            for (int i = 0; i < reader.AttributeCount; i++)
                            {
                                reader.MoveToAttribute(i);
                                switch (reader.Name.ToLower())
                                {
                                case "ispermalink":
                                    try
                                    {
                                        guid.PermaLink = bool.Parse(reader.Value);
                                    }
                                    catch (Exception e)
                                    {
                                        exceptions.Add(e);
                                    }
                                    break;
                                }
                            }
                            break;

                        case "category":
                            category = new RssCategory();
                            if ((string)xmlNodeStack.Peek() == "channel")
                            {
                                channel.Categories.Add(category);
                            }
                            else
                            {
                                item.Categories.Add(category);
                            }
                            for (int i = 0; i < reader.AttributeCount; i++)
                            {
                                reader.MoveToAttribute(i);
                                switch (reader.Name.ToLower())
                                {
                                case "url":
                                    goto case "domain";

                                case "domain":
                                    category.Domain = reader.Value;
                                    break;
                                }
                            }
                            break;

                        case "channel":
                            channel   = new RssChannel();
                            textInput = null;
                            image     = null;
                            cloud     = null;
                            source    = null;
                            enclosure = null;
                            category  = null;
                            item      = null;
                            break;

                        case "image":
                            image         = new RssImage();
                            channel.Image = image;
                            break;

                        case "textinput":
                            textInput         = new RssTextInput();
                            channel.TextInput = textInput;
                            break;

                        case "cloud":
                            pushElement   = false;
                            cloud         = new RssCloud();
                            channel.Cloud = cloud;
                            for (int i = 0; i < reader.AttributeCount; i++)
                            {
                                reader.MoveToAttribute(i);
                                switch (reader.Name.ToLower())
                                {
                                case "domain":
                                    cloud.Domain = reader.Value;
                                    break;

                                case "port":
                                    try
                                    {
                                        cloud.Port = ushort.Parse(reader.Value);
                                    }
                                    catch (Exception e)
                                    {
                                        exceptions.Add(e);
                                    }
                                    break;

                                case "path":
                                    cloud.Path = reader.Value;
                                    break;

                                case "registerprocedure":
                                    cloud.RegisterProcedure = reader.Value;
                                    break;

                                case "protocol":
                                    switch (reader.Value.ToLower())
                                    {
                                    case "xml-rpc":
                                        cloud.Protocol = RssCloudProtocol.XmlRpc;
                                        break;

                                    case "soap":
                                        cloud.Protocol = RssCloudProtocol.Soap;
                                        break;

                                    case "http-post":
                                        cloud.Protocol = RssCloudProtocol.HttpPost;
                                        break;

                                    default:
                                        cloud.Protocol = RssCloudProtocol.Empty;
                                        break;
                                    }
                                    break;
                                }
                            }
                            break;

                        case "rss":
                            for (int i = 0; i < reader.AttributeCount; i++)
                            {
                                reader.MoveToAttribute(i);
                                if (reader.Name.ToLower() == "version")
                                {
                                    switch (reader.Value)
                                    {
                                    case "0.91":
                                        rssVersion = RssVersion.RSS091;
                                        break;

                                    case "0.92":
                                        rssVersion = RssVersion.RSS092;
                                        break;

                                    case "2.0":
                                        rssVersion = RssVersion.RSS20;
                                        break;

                                    default:
                                        rssVersion = RssVersion.NotSupported;
                                        break;
                                    }
                                }
                            }
                            break;

                        case "rdf":
                            for (int i = 0; i < reader.AttributeCount; i++)
                            {
                                reader.MoveToAttribute(i);
                                if (reader.Name.ToLower() == "version")
                                {
                                    switch (reader.Value)
                                    {
                                    case "0.90":
                                        rssVersion = RssVersion.RSS090;
                                        break;

                                    case "1.0":
                                        rssVersion = RssVersion.RSS10;
                                        break;

                                    default:
                                        rssVersion = RssVersion.NotSupported;
                                        break;
                                    }
                                }
                            }
                            break;

                        case "geo:lat":
                        case "geo:long":
                        case "geo:point":
                        case "georss:point":
                        case "georss:elev":
                        case "georss:radius":
                            if (item.GeoPoint == null)
                            {
                                item.GeoPoint = new RssGeoPoint();
                            }
                            break;
                        }
                        if (pushElement)
                        {
                            xmlNodeStack.Push(readerName);
                        }
                        break;
                    }

                    case XmlNodeType.EndElement:
                    {
                        if (xmlNodeStack.Count == 1)
                        {
                            break;
                        }
                        string childElementName  = (string)xmlNodeStack.Pop();
                        string parentElementName = (string)xmlNodeStack.Peek();
                        switch (childElementName)                                 // current element
                        {
                        // item classes
                        case "item":
                            rssElement = item;
                            readData   = false;
                            break;

                        case "source":
                            source.Name = elementText.ToString();
                            rssElement  = source;
                            readData    = false;
                            break;

                        case "enclosure":
                            rssElement = enclosure;
                            readData   = false;
                            break;

                        case "guid":
                            guid.Name  = elementText.ToString();
                            rssElement = guid;
                            readData   = false;
                            break;

                        case "category":                                         // parent is either item or channel
                            category.Name = elementText.ToString();
                            rssElement    = category;
                            readData      = false;
                            break;

                        // channel classes
                        case "channel":
                            if (wroteChannel)
                            {
                                wroteChannel = false;
                            }
                            else
                            {
                                wroteChannel = true;
                                rssElement   = channel;
                                readData     = false;
                            }
                            break;

                        case "textinput":
                            rssElement = textInput;
                            readData   = false;
                            break;

                        case "image":
                            rssElement = image;
                            readData   = false;
                            break;

                        case "cloud":
                            rssElement = cloud;
                            readData   = false;
                            break;
                        }
                        switch (parentElementName)                                 // parent element
                        {
                        case "item":
                            switch (childElementName)
                            {
                            case "title":
                                item.Title = elementText.ToString();
                                break;

                            case "link":
                                item.Link = new Uri(elementText.ToString());
                                break;

                            case "description":
                                item.Description = elementText.ToString();
                                break;

                            case "author":
                                item.Author = elementText.ToString();
                                break;

                            case "comments":
                                item.Comments = elementText.ToString();
                                break;

                            case "pubdate":
                                try
                                {
                                    item.PubDate = DateTime.Parse(elementText.ToString());
                                }
                                catch (Exception e)
                                {
                                    try {
                                        string tmp = elementText.ToString();
                                        tmp          = tmp.Substring(0, tmp.Length - 5);
                                        tmp         += "GMT";
                                        item.PubDate = DateTime.Parse(tmp);
                                    }
                                    catch
                                    {
                                        exceptions.Add(e);
                                    }
                                }
                                break;

                            case "geo:lat":
                                try
                                {
                                    item.GeoPoint.Lat = float.Parse(elementText.ToString());
                                }
                                catch (Exception e)
                                {
                                    exceptions.Add(e);
                                }
                                break;

                            case "geo:long":
                                try
                                {
                                    item.GeoPoint.Lon = float.Parse(elementText.ToString());
                                }
                                catch (Exception e)
                                {
                                    exceptions.Add(e);
                                }
                                break;

                            case "georss:point":
                                try
                                {
                                    string[] coords = elementText.ToString().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (coords.Length == 2)
                                    {
                                        item.GeoPoint.Lat = float.Parse(coords[0]);
                                        item.GeoPoint.Lon = float.Parse(coords[1]);
                                    }
                                }
                                catch (Exception e)
                                {
                                    exceptions.Add(e);
                                }
                                break;
                            }
                            break;

                        case "channel":
                            switch (childElementName)
                            {
                            case "title":
                                channel.Title = elementText.ToString();
                                break;

                            case "link":
                                try
                                {
                                    channel.Link = new Uri(elementText.ToString());
                                }
                                catch (Exception e)
                                {
                                    exceptions.Add(e);
                                }
                                break;

                            case "description":
                                channel.Description = elementText.ToString();
                                break;

                            case "language":
                                channel.Language = elementText.ToString();
                                break;

                            case "copyright":
                                channel.Copyright = elementText.ToString();
                                break;

                            case "managingeditor":
                                channel.ManagingEditor = elementText.ToString();
                                break;

                            case "webmaster":
                                channel.WebMaster = elementText.ToString();
                                break;

                            case "rating":
                                channel.Rating = elementText.ToString();
                                break;

                            case "pubdate":
                                try
                                {
                                    channel.PubDate = DateTime.Parse(elementText.ToString());
                                }
                                catch (Exception e)
                                {
                                    exceptions.Add(e);
                                }
                                break;

                            case "lastbuilddate":
                                try
                                {
                                    channel.LastBuildDate = DateTime.Parse(elementText.ToString());
                                }
                                catch (Exception e)
                                {
                                    exceptions.Add(e);
                                }
                                break;

                            case "generator":
                                channel.Generator = elementText.ToString();
                                break;

                            case "docs":
                                channel.Docs = elementText.ToString();
                                break;

                            case "ttl":
                                try
                                {
                                    channel.TimeToLive = int.Parse(elementText.ToString());
                                }
                                catch (Exception e)
                                {
                                    exceptions.Add(e);
                                }
                                break;
                            }
                            break;

                        case "image":
                            switch (childElementName)
                            {
                            case "url":
                                try
                                {
                                    image.Url = new Uri(elementText.ToString());
                                }
                                catch (Exception e)
                                {
                                    exceptions.Add(e);
                                }
                                break;

                            case "title":
                                image.Title = elementText.ToString();
                                break;

                            case "link":
                                try
                                {
                                    image.Link = new Uri(elementText.ToString());
                                }
                                catch (Exception e)
                                {
                                    exceptions.Add(e);
                                }
                                break;

                            case "description":
                                image.Description = elementText.ToString();
                                break;

                            case "width":
                                try
                                {
                                    image.Width = Byte.Parse(elementText.ToString());
                                }
                                catch (Exception e)
                                {
                                    exceptions.Add(e);
                                }
                                break;

                            case "height":
                                try
                                {
                                    image.Height = Byte.Parse(elementText.ToString());
                                }
                                catch (Exception e)
                                {
                                    exceptions.Add(e);
                                }
                                break;
                            }
                            break;

                        case "textinput":
                            switch (childElementName)
                            {
                            case "title":
                                textInput.Title = elementText.ToString();
                                break;

                            case "description":
                                textInput.Description = elementText.ToString();
                                break;

                            case "name":
                                textInput.Name = elementText.ToString();
                                break;

                            case "link":
                                try
                                {
                                    textInput.Link = new Uri(elementText.ToString());
                                }
                                catch (Exception e)
                                {
                                    exceptions.Add(e);
                                }
                                break;
                            }
                            break;

                        case "skipdays":
                            if (childElementName == "day")
                            {
                                channel.SkipDays |= Day.Parse(elementText.ToString());
                            }
                            break;

                        case "skiphours":
                            if (childElementName == "hour")
                            {
                                channel.SkipHours |= Hour.Parse(elementText.ToString());
                            }
                            break;
                        }
                        break;
                    }

                    case XmlNodeType.Text:
                        elementText.Append(reader.Value);
                        break;

                    case XmlNodeType.CDATA:
                        elementText.Append(reader.Value);
                        break;
                    }
                }
            }while (readData);
            return(rssElement);
        }
        private void TryIndent(TextArea textArea, int begin, int end)
        {
            string      currentIndentation = "";
            Stack       tagStack           = new Stack();
            IDocument   document           = textArea.Document;
            string      tab             = Tab.GetIndentationString(document);
            int         nextLine        = begin; // in #dev coordinates
            bool        wasEmptyElement = false;
            XmlNodeType lastType        = XmlNodeType.XmlDeclaration;

            // TextReader line number begin with 1, #dev line numbers with 0
            using (StringReader stringReader = new StringReader(document.TextContent)) {
                XmlTextReader r = new XmlTextReader(stringReader);
                r.XmlResolver = null;                 // prevent XmlTextReader from loading external DTDs
                while (r.Read())
                {
                    if (wasEmptyElement)
                    {
                        wasEmptyElement = false;
                        if (tagStack.Count == 0)
                        {
                            currentIndentation = "";
                        }
                        else
                        {
                            currentIndentation = (string)tagStack.Pop();
                        }
                    }
                    if (r.NodeType == XmlNodeType.EndElement)
                    {
                        if (tagStack.Count == 0)
                        {
                            currentIndentation = "";
                        }
                        else
                        {
                            currentIndentation = (string)tagStack.Pop();
                        }
                    }

                    while (r.LineNumber > nextLine)                       // caution: here we compare 1-based and 0-based line numbers
                    {
                        if (nextLine > end)
                        {
                            break;
                        }
                        if (lastType == XmlNodeType.CDATA || lastType == XmlNodeType.Comment)
                        {
                            nextLine += 1;
                            continue;
                        }
                        // set indentation of 'nextLine'
                        LineSegment line     = document.GetLineSegment(nextLine);
                        string      lineText = document.GetText(line);

                        string newText;
                        // special case: opening tag has closing bracket on extra line: remove one indentation level
                        if (lineText.Trim() == ">")
                        {
                            newText = (string)tagStack.Peek() + lineText.Trim();
                        }
                        else
                        {
                            newText = currentIndentation + lineText.Trim();
                        }

                        if (newText != lineText)
                        {
                            document.Replace(line.Offset, line.Length, newText);
                        }
                        nextLine += 1;
                    }
                    if (r.LineNumber > end)
                    {
                        break;
                    }
                    wasEmptyElement = r.NodeType == XmlNodeType.Element && r.IsEmptyElement;
                    string attribIndent = null;
                    if (r.NodeType == XmlNodeType.Element)
                    {
                        tagStack.Push(currentIndentation);
                        if (r.LineNumber < begin)
                        {
                            currentIndentation = GetIndentation(textArea, r.LineNumber - 1);
                        }
                        if (r.Name.Length < 16)
                        {
                            attribIndent = currentIndentation + new String(' ', 2 + r.Name.Length);
                        }
                        else
                        {
                            attribIndent = currentIndentation + tab;
                        }
                        currentIndentation += tab;
                    }
                    lastType = r.NodeType;
                    if (r.NodeType == XmlNodeType.Element && r.HasAttributes)
                    {
                        int startLine = r.LineNumber;
                        r.MoveToAttribute(0);                         // move to first attribute
                        if (r.LineNumber != startLine)
                        {
                            attribIndent = currentIndentation;                             // change to tab-indentation
                        }
                        r.MoveToAttribute(r.AttributeCount - 1);
                        while (r.LineNumber > nextLine)                           // caution: here we compare 1-based and 0-based line numbers
                        {
                            if (nextLine > end)
                            {
                                break;
                            }
                            // set indentation of 'nextLine'
                            LineSegment line     = document.GetLineSegment(nextLine);
                            string      lineText = document.GetText(line);
                            string      newText  = attribIndent + lineText.Trim();
                            if (newText != lineText)
                            {
                                document.Replace(line.Offset, line.Length, newText);
                            }
                            nextLine += 1;
                        }
                    }
                }
                r.Close();
            }
        }
Exemplo n.º 29
0
        private void _DaemonPipe_OnReceiveLine(string line)
        {
            XmlTextReader reader = new XmlTextReader(new StringReader(line));

            reader.DtdProcessing = DtdProcessing.Ignore;

            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                case XmlNodeType.Element:
                {
                    if (reader.Depth == 0)
                    {
                        isEvent = (reader.Name == "Event");

                        if (isEvent || reader.Name == "Response")
                        {
                            for (int i = 0; i < reader.AttributeCount; i++)
                            {
                                reader.MoveToAttribute(i);

                                switch (reader.Name)
                                {
//                                         case "requestId":
//                                             uuidString = reader.Value;
//                                             break;
                                case "action":
                                    actionString = reader.Value;
                                    break;

                                case "type":
                                    eventTypeString = reader.Value;
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        switch (reader.Name)
                        {
                        case "InputXml":
                            cookie = -1;

                            // Parse through here to get the cookie value
                            reader.Read();
                            if (reader.Name == "Request")
                            {
                                for (int i = 0; i < reader.AttributeCount; i++)
                                {
                                    reader.MoveToAttribute(i);

                                    if (reader.Name == "requestId")
                                    {
                                        Int32.TryParse(reader.Value, out cookie);
                                        break;
                                    }
                                }
                            }

                            if (cookie == -1)
                            {
                                Logger.Log("VoiceManager._DaemonPipe_OnReceiveLine(): Failed to parse InputXml for the cookie",
                                           Helpers.LogLevel.Warning, Client);
                            }
                            break;

                        case "CaptureDevices":
                            _CaptureDevices.Clear();
                            break;

                        case "RenderDevices":
                            _RenderDevices.Clear();
                            break;

//                                 case "ReturnCode":
//                                     returnCode = reader.ReadElementContentAsInt();
//                                     break;
                        case "StatusCode":
                            statusCode = reader.ReadElementContentAsInt();
                            break;

                        case "StatusString":
                            statusString = reader.ReadElementContentAsString();
                            break;

                        case "State":
                            state = reader.ReadElementContentAsInt();
                            break;

                        case "ConnectorHandle":
                            connectorHandle = reader.ReadElementContentAsString();
                            break;

                        case "AccountHandle":
                            accountHandle = reader.ReadElementContentAsString();
                            break;

                        case "SessionHandle":
                            sessionHandle = reader.ReadElementContentAsString();
                            break;

                        case "URI":
                            uriString = reader.ReadElementContentAsString();
                            break;

                        case "IsChannel":
                            isChannel = reader.ReadElementContentAsBoolean();
                            break;

                        case "Name":
                            nameString = reader.ReadElementContentAsString();
                            break;

//                                 case "AudioMedia":
//                                     audioMediaString = reader.ReadElementContentAsString();
//                                     break;
                        case "ChannelName":
                            nameString = reader.ReadElementContentAsString();
                            break;

                        case "ParticipantURI":
                            uriString = reader.ReadElementContentAsString();
                            break;

                        case "DisplayName":
                            displayNameString = reader.ReadElementContentAsString();
                            break;

                        case "AccountName":
                            nameString = reader.ReadElementContentAsString();
                            break;

                        case "ParticipantType":
                            participantType = reader.ReadElementContentAsInt();
                            break;

                        case "IsLocallyMuted":
                            isLocallyMuted = reader.ReadElementContentAsBoolean();
                            break;

                        case "IsModeratorMuted":
                            isModeratorMuted = reader.ReadElementContentAsBoolean();
                            break;

                        case "IsSpeaking":
                            isSpeaking = reader.ReadElementContentAsBoolean();
                            break;

                        case "Volume":
                            volume = reader.ReadElementContentAsInt();
                            break;

                        case "Energy":
                            energy = reader.ReadElementContentAsFloat();
                            break;

                        case "MicEnergy":
                            energy = reader.ReadElementContentAsFloat();
                            break;

                        case "ChannelURI":
                            uriString = reader.ReadElementContentAsString();
                            break;

                        case "ChannelListResult":
                            _ChannelMap[nameString] = uriString;
                            break;

                        case "CaptureDevice":
                            reader.Read();
                            _CaptureDevices.Add(reader.ReadElementContentAsString());
                            break;

                        case "CurrentCaptureDevice":
                            reader.Read();
                            nameString = reader.ReadElementContentAsString();
                            break;

                        case "RenderDevice":
                            reader.Read();
                            _RenderDevices.Add(reader.ReadElementContentAsString());
                            break;

                        case "CurrentRenderDevice":
                            reader.Read();
                            nameString = reader.ReadElementContentAsString();
                            break;
                        }
                    }

                    break;
                }

                case XmlNodeType.EndElement:
                    if (reader.Depth == 0)
                    {
                        ProcessEvent();
                    }
                    break;
                }
            }

            if (isEvent)
            {
            }

            //Client.DebugLog("VOICE: " + line);
        }
        private List <ShippingOption> ParseResponse(string response, bool isDomestic, ref string error)
        {
            var shippingOptions = new List <ShippingOption>();

            string postageStr             = isDomestic ? "Postage" : "Service";
            string mailServiceStr         = isDomestic ? "MailService" : "SvcDescription";
            string rateStr                = isDomestic ? "Rate" : "Postage";
            string classStr               = isDomestic ? "CLASSID" : "ID";
            string carrierServicesOffered = isDomestic ? _uspsSettings.CarrierServicesOfferedDomestic : _uspsSettings.CarrierServicesOfferedInternational;

            using (var sr = new StringReader(response))
                using (var tr = new XmlTextReader(sr))
                {
                    do
                    {
                        tr.Read();

                        if ((tr.Name == "Error") && (tr.NodeType == XmlNodeType.Element))
                        {
                            string errorText = "";
                            while (tr.Read())
                            {
                                if ((tr.Name == "Description") && (tr.NodeType == XmlNodeType.Element))
                                {
                                    errorText += "Error Desc: " + tr.ReadString();
                                }
                                if ((tr.Name == "HelpContext") && (tr.NodeType == XmlNodeType.Element))
                                {
                                    errorText += "USPS Help Context: " + tr.ReadString() + ". ";
                                }
                            }
                            error = "USPS Error returned: " + errorText;
                        }

                        if ((tr.Name == postageStr) && (tr.NodeType == XmlNodeType.Element))
                        {
                            string serviceId = string.Empty;

                            // Find the ID for the service
                            if (tr.HasAttributes)
                            {
                                for (int i = 0; i < tr.AttributeCount; i++)
                                {
                                    tr.MoveToAttribute(i);
                                    if (tr.Name.Equals(classStr))
                                    {
                                        // Add delimiters [] so that single digit IDs aren't found in mutli-digit IDs
                                        serviceId = String.Format("[{0}]", tr.Value);
                                        break;
                                    }
                                }
                            }

                            // Go to the next rate if the service ID is not in the list of services to offer
                            if (!String.IsNullOrEmpty(serviceId) &&
                                !String.IsNullOrEmpty(carrierServicesOffered) &&
                                !carrierServicesOffered.Contains(serviceId))
                            {
                                continue;
                            }

                            string serviceCode = string.Empty;
                            string postalRate  = string.Empty;

                            do
                            {
                                tr.Read();

                                if ((tr.Name == mailServiceStr) && (tr.NodeType == XmlNodeType.Element))
                                {
                                    serviceCode = tr.ReadString();

                                    tr.ReadEndElement();
                                    if ((tr.Name == mailServiceStr) && (tr.NodeType == XmlNodeType.EndElement))
                                    {
                                        break;
                                    }
                                }

                                if ((tr.Name == rateStr) && (tr.NodeType == XmlNodeType.Element))
                                {
                                    postalRate = tr.ReadString();
                                    tr.ReadEndElement();
                                    if ((tr.Name == rateStr) && (tr.NodeType == XmlNodeType.EndElement))
                                    {
                                        break;
                                    }
                                }
                            }while (!((tr.Name == postageStr) && (tr.NodeType == XmlNodeType.EndElement)));

                            //USPS issue fixed
                            char   reg = (char)174; // registered sign "\u00AE"
                            string tm  = "\u2122";  // trademark sign
                            serviceCode = serviceCode.Replace("&lt;sup&gt;&amp;reg;&lt;/sup&gt;", reg.ToString());
                            serviceCode = serviceCode.Replace("&lt;sup&gt;&amp;trade;&lt;/sup&gt;", tm);

                            ShippingOption shippingOption = shippingOptions.Find((s) => s.Name == serviceCode);
                            if (shippingOption == null)
                            {
                                shippingOption      = new ShippingOption();
                                shippingOption.Name = serviceCode;
                                shippingOptions.Add(shippingOption);
                            }
                            shippingOption.Rate += Convert.ToDecimal(postalRate, new CultureInfo("en-US"));
                        }
                    }while (!tr.EOF);
                }
            return(shippingOptions);
        }
Exemplo n.º 31
0
        private static void ReadFileImport(Mobile from, XmlTextReader xml)
        {
            ArrayList array = new ArrayList();

            int tileid = 0, x = 0, y = 0, z = 0, hue = 0;

            int count = 0;

            while (xml.Read())
            {
                if (xml.MoveToAttribute("TileID"))
                {
                    tileid = Utility.ToInt32(xml.Value);
                }

                if (xml.MoveToAttribute("X"))
                {
                    x = Utility.ToInt32(xml.Value);
                }

                if (xml.MoveToAttribute("Y"))
                {
                    y = Utility.ToInt32(xml.Value);
                }

                if (xml.MoveToAttribute("Z"))
                {
                    z = Utility.ToInt32(xml.Value);
                }

                if (xml.MoveToAttribute("Hue"))
                {
                    hue = Utility.ToInt32(xml.Value);
                }

                array.Add(new StaticImportEntry(tileid, x, y, z, hue));

                count++;

                if (EnableLogFile)
                {
                    CreateLogFile(String.Format("[{5}] ArrayList Property: ( TileID: {0}, X: {1}, Y: {2}, Z: {3}, Hue: {4} )", tileid, x, y, z, hue, count), true);
                }
            }

            count = 0;

            foreach (StaticImportEntry s in array)
            {
                Static item = new Static(s.TileID);
                item.Hue = s.Hue;
                item.X   = s.X;
                item.Y   = s.Y;
                item.Z   = s.Z;

                item.MoveToWorld(new Point3D(s.X, s.Y, s.Z), MapID);
                item.Movable = false;
                count++;
            }

            if (EnableLogFile)
            {
                CreateLogFile(String.Format("Imported {0} items to [{1}].", count, MapID.Name), true);
            }

            from.SendMessage("Imported {0} items to {1}.", count, MapID.Name);
        }
        protected void LastChangeSink(CpAVTransport sender, string LC)
        {
            if (LC == "")
            {
                return;
            }
            //LC = UPnPStringFormatter.UnEscapeString(LC);
            if (LC.Substring(0, 1) != "<")
            {
                LC = UPnPStringFormatter.UnEscapeString(LC);
            }
            if (LC.Substring(0, 1) != "<")
            {
                LC = UPnPStringFormatter.UnEscapeString(LC);
            }

            StringReader  MyString = new StringReader(LC);
            XmlTextReader XMLDoc   = new XmlTextReader(MyString);

            Hashtable T = new Hashtable();

            int    ID        = -1;
            string VarName   = "";
            string VarValue  = "";
            string AttrName  = "";
            string AttrValue = "";

            XMLDoc.Read();
            XMLDoc.MoveToContent();

            XMLDoc.Read();
            XMLDoc.MoveToContent();

            while ((XMLDoc.LocalName != "Event") && (XMLDoc.EOF == false))
            {
                // At Start, should be InstanceID
                if (XMLDoc.LocalName == "InstanceID")
                {
                    XMLDoc.MoveToAttribute("val");
                    ID = int.Parse(XMLDoc.GetAttribute("val"));
                    if (T.ContainsKey(ID) == false)
                    {
                        T[ID] = new Hashtable();
                    }
                    XMLDoc.MoveToContent();

                    XMLDoc.Read();
                    XMLDoc.MoveToContent();

                    while (XMLDoc.LocalName != "InstanceID")
                    {
                        if (XMLDoc.IsStartElement() == true)
                        {
                            VarName   = XMLDoc.LocalName;
                            VarValue  = "";
                            AttrName  = "";
                            AttrValue = "";

                            for (int a_idx = 0; a_idx < XMLDoc.AttributeCount; ++a_idx)
                            {
                                XMLDoc.MoveToAttribute(a_idx);
                                if (XMLDoc.LocalName == "val")
                                {
                                    VarValue = UPnPStringFormatter.UnEscapeString(XMLDoc.GetAttribute(a_idx));
                                }
                                else
                                {
                                    AttrName  = XMLDoc.LocalName;
                                    AttrValue = XMLDoc.GetAttribute(a_idx);
                                }
                            }

                            XMLDoc.MoveToContent();

                            if (AttrName == "")
                            {
                                ((Hashtable)T[ID])[VarName] = VarValue;
                            }
                            else
                            {
                                if (((Hashtable)T[ID]).ContainsKey(VarName) == false)
                                {
                                    ((Hashtable)T[ID])[VarName] = new Hashtable();
                                }
                                if (((Hashtable)((Hashtable)T[ID])[VarName]).ContainsKey(AttrName) == false)
                                {
                                    ((Hashtable)((Hashtable)T[ID])[VarName])[AttrName] = new Hashtable();
                                }
                                ((Hashtable)((Hashtable)((Hashtable)T[ID])[VarName])[AttrName])[AttrValue] = VarValue;
                            }
                        }
                        XMLDoc.Read();
                        XMLDoc.MoveToContent();
                    }
                }
                else
                {
                    XMLDoc.Skip();
                }
                XMLDoc.Read();
                XMLDoc.MoveToContent();
            }

            XMLDoc.Close();


            IDictionaryEnumerator inEn = T.GetEnumerator();
            IDictionaryEnumerator EvEn;
            Hashtable             TT;
            string TempString;
            DText  TempParser = new DText();

            while (inEn.MoveNext())
            {
                if (inEn.Key.ToString() == InstanceID)
                {
                    TT   = (Hashtable)inEn.Value;
                    EvEn = TT.GetEnumerator();
                    while (EvEn.MoveNext())
                    {
                        switch ((string)EvEn.Key)
                        {
                        case "AVTransportURI":
                            _AVTransportURI = (string)EvEn.Value;
                            if (OnAVTransportURIChanged != null)
                            {
                                OnAVTransportURIChanged(this);
                            }
                            break;

                        case "TransportState":
                            _PlayState = (string)EvEn.Value;
                            if (OnPlayStateChanged != null)
                            {
                                OnPlayStateChanged(this);
                            }
                            break;

                        case "CurrentTrackDuration":
                            TempString          = (string)EvEn.Value;
                            TempParser.ATTRMARK = ":";
                            TempParser[0]       = TempString;
                            try
                            {
                                this._CurrentDuration = new TimeSpan(int.Parse(TempParser[1]), int.Parse(TempParser[2]), int.Parse(TempParser[3]));
                            }
                            catch (Exception)
                            {}
                            if (this.OnCurrentPositionChanged != null)
                            {
                                this.OnCurrentPositionChanged(this);
                            }
                            break;

                        case "RelativeTimePosition":
                            TempString            = (string)EvEn.Value;
                            TempParser.ATTRMARK   = ":";
                            TempParser[0]         = TempString;
                            this._CurrentPosition = new TimeSpan(int.Parse(TempParser[1]), int.Parse(TempParser[2]), int.Parse(TempParser[3]));
                            if (this.OnCurrentPositionChanged != null)
                            {
                                this.OnCurrentPositionChanged(this);
                            }
                            break;

                        case "NumberOfTracks":
                            try
                            {
                                _NumberOfTracks = UInt32.Parse((string)EvEn.Value);
                                if (OnNumberOfTracksChanged != null)
                                {
                                    OnNumberOfTracksChanged(this);
                                }
                            }
                            catch (Exception)
                            {}
                            break;

                        case "CurrentTrack":
                            try
                            {
                                _CurrentTrack = UInt32.Parse((string)EvEn.Value);
                                if (OnCurrentTrackChanged != null)
                                {
                                    OnCurrentTrackChanged(this);
                                }
                            }
                            catch (Exception)
                            {}
                            break;

                        case "CurrentTrackURI":
                            _TrackURI = (string)EvEn.Value;
                            if (OnTrackURIChanged != null)
                            {
                                OnTrackURIChanged(this);
                            }
                            break;

                        case "TransportStatus":
                            _TransportStatus = (string)EvEn.Value;
                            if (OnTransportStatusChanged != null)
                            {
                                OnTransportStatusChanged(this);
                            }
                            break;

                        case "AVTransportURIMetaData":
                            _AVTransportMetaData = (string)EvEn.Value;
                            if (this.OnCurrentURIMetaDataChanged != null)
                            {
                                OnCurrentURIMetaDataChanged(this);
                            }
                            break;

                        case "CurrentPlayMode":
                            _CurrentPlayMode = (string)EvEn.Value;
                            if (this.OnCurrentPlayModeChanged != null)
                            {
                                OnCurrentPlayModeChanged(this);
                            }
                            break;
                        }
                    }
                }
            }
        }
Exemplo n.º 33
0
    //加载xm文件
    public static DialogWriter LoadXMLEvent()
    {
        bool m_isTalkNode = true;


        if (Application.platform == RuntimePlatform.OSXPlayer)
        {
            Console.Log("sfdbdfsdgsfdgsfdds");
            path = Application.dataPath + "/Resources/Data/StreamingAssets/dialogWriter.xml";
            Console.Log(path);
        }
        else if (Application.platform == RuntimePlatform.IPhonePlayer)
        {
            path = Application.dataPath + "/Raw/";
        }
        else if (Application.platform == RuntimePlatform.Android)
        {
            path = "jar:file//" + Application.dataPath + "!/assets/";
        }
        //} else if(Application.platform == RuntimePlatform.){
        //	path = Application.dataPath + "/StreamingAssets/";
        //}


        XmlReader reader = new XmlTextReader(path);

        //提前设置的变量,用于保存读取文件时的各个子节点
        DialogWriter  newDialogWriter  = null;
        DialogEvent   newDialogEvent   = null;
        TalkNode      newTalkNode      = null;
        SelectionNode newSelectionNode = null;
        TalkContent   newTalkContent   = null;
        string        newSelect        = "";

        newDialogWriter = new DialogWriter();
        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element)
            {
                if (reader.LocalName == "DialogWriter")
                {
                    if (newDialogWriter != null)
                    {
                    }
                    //不会执行
                }
                else if (reader.LocalName == "Event")
                {
                    newDialogEvent = new DialogEvent("");
                    for (int i = 0; i < reader.AttributeCount; i++)
                    {
                        reader.MoveToAttribute(i);
                        if (reader.Name == "Name")
                        {
                            newDialogEvent.m_name = reader.Value;
                        }
                        else if (reader.Name == "EventOrder")
                        {
                            newDialogEvent.m_eventOrder = int.Parse(reader.Value);
                        }
                    }

                    if (newDialogWriter != null)
                    {
                        newDialogWriter.m_dialogEventList.Add(newDialogEvent);
                    }
                }
                else if (reader.LocalName == "TalkNode")
                {
                    newTalkNode = new TalkNode("");


                    for (int i = 0; i < reader.AttributeCount; i++)
                    {
                        reader.MoveToAttribute(i);
                        if (reader.Name == "Name")
                        {
                            newTalkNode.m_name = reader.Value;
                        }
                        else if (reader.Name == "NodeType")
                        {
                            newTalkNode.m_dialogType = (DialogNode.NodeType)System.Enum.Parse(typeof(DialogNode.NodeType), reader.Value);
                        }
                    }

                    //不是选择分支下的对话节点
                    if (m_isTalkNode)
                    {
                        if (newDialogEvent != null)
                        {
                            newDialogEvent.m_nodeList.Add(newTalkNode);
                        }
                    }
                    else
                    {
                        if (newSelectionNode != null)
                        {
                            newSelectionNode.m_selection [newSelect] = newTalkNode;
                            //每次都重新设为true
                            m_isTalkNode = true;
                        }
                    }
                }
                else if (reader.LocalName == "Background")
                {
                    for (int i = 0; i < reader.AttributeCount; i++)
                    {
                        reader.MoveToAttribute(i);

                        if (reader.Name == "Name")
                        {
                            newTalkNode.m_background.Add(reader.Value);
                        }
                    }
                }
                else if (reader.LocalName == "Tachie")
                {
                    for (int i = 0; i < reader.AttributeCount; i++)
                    {
                        reader.MoveToAttribute(i);
                        if (reader.Name == "Name")
                        {
                            newTalkNode.m_tachie.Add(reader.Value);
                        }
                    }
                }
                else if (reader.LocalName == "TalkContent")
                {
                    newTalkContent = new TalkContent();
                    for (int i = 0; i < reader.AttributeCount; i++)
                    {
                        reader.MoveToAttribute(i);
                        if (reader.Name == "Background")
                        {
                            newTalkContent.m_backGround = int.Parse(reader.Value);
                        }
                        else if (reader.Name == "Tachie")
                        {
                            newTalkContent.m_tachie = int.Parse(reader.Value);
                        }
                        else if (reader.Name == "Name")
                        {
                            newTalkContent.m_name = reader.Value;
                        }
                        else if (reader.Name == "Content")
                        {
                            newTalkContent.m_content = reader.Value;
                        }
                    }

                    if (newTalkNode != null)
                    {
                        newTalkNode.m_talkContents.Add(newTalkContent);
                    }
                }
                else if (reader.LocalName == "SelectionNode")
                {
                    newSelectionNode = new SelectionNode("");
                    for (int i = 0; i < reader.AttributeCount; i++)
                    {
                        reader.MoveToAttribute(i);
                        if (reader.Name == "Name")
                        {
                            newSelectionNode.m_name = reader.Value;
                        }
                    }

                    if (newDialogEvent != null)
                    {
                        newDialogEvent.m_nodeList.Add(newSelectionNode);
                    }
                }
                else if (reader.LocalName == "Select")
                {
                    m_isTalkNode = false;

                    for (int i = 0; i < reader.AttributeCount; i++)
                    {
                        reader.MoveToAttribute(i);
                        if (reader.Name == "Select")
                        {
                            //把数值临时保存
                            newSelect = reader.Value;
                            newSelectionNode.m_selection.Add(reader.Value, new TalkNode(""));
                        }
                    }
                }
            }
        }


        return(newDialogWriter);
    }
Exemplo n.º 34
0
        /*********************************************************************/
        /* create the new Rt object for the class.                           */
        /*********************************************************************/
        private void CreateRtElement(XmlTextReader inFile, XmlTextWriter xmlOutput)
        {
            string stackClass = "", stackNum = "", baseClassName = holdNode;
            int    modNum = 0, fieldNum = 0, classNum = 0;

            StartElem = false;
            if (holdNode != "LangProject")
            {
                RTClass clas = new RTClass();
                stackClasses.Push(clas);
                listClasses.Add(clas);
                currentRT = clas;
            }
            else
            {
                currentRT = langProjClass;
            }

            if (stackElements.Count > 0)
            {
                stackClass = GetElementName(stackElements.Peek());
                stackNum   = (GetElementNumber(stackElements.Peek())).PadLeft(3, '0');
                modNum     = int.Parse(stackNum.Substring(0, 1));
                classNum   = int.Parse(stackNum.Substring(1));
                modList.TryGetValue(modNum, out dicClass);

                dicClass.TryGetValue(classNum, out hClass);
                hClass.fields.TryGetValue(stackClass, out fieldNum);
                if (stackNum != "000" && fieldNum != 0)
                {
                    currentRT.ownFlid = int.Parse((stackNum + (fieldNum.ToString().PadLeft(3, '0'))).TrimStart('0'));
                }
                currentRT.owningGuid = guidStack.Peek();
            }

            // Build Hierarchy
            do
            {
                classList.TryGetValue(baseClassName, out hClass);
                classNum = hClass.ClassNum;
                currentRT.hierarchy.Add(int.Parse(hClass.ModNum + classNum.ToString().PadLeft(3, '0')));
                if (baseClassName != "CmObject")
                {
                    classList.TryGetValue(baseClassName, out hClass);
                    baseClassName = hClass.BaseClassName;
                }
            }while (currentRT.hierarchy[currentRT.hierarchy.Count - 1] != 0);

            StartClass          = true;
            currentRT.ClassName = holdNode;
            for (int i = 0; i < inFile.AttributeCount; i++)
            {
                inFile.MoveToAttribute(i);
                if (inFile.Name == "id")
                {
                    currentRT.Guid = inFile.Value.Substring(1);
                    guidStack.Push(currentRT.Guid);
                }
                else
                {
                    throw new Exception("Attribute " + inFile.Name + " exists for " + holdNode);
                }
            }
        }
Exemplo n.º 35
0
        private void FormXmlViewer_Load(object sender, EventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            try
            {
                if (TopLeft.X != 0 && TopLeft.Y != 0)
                {
                    Left = (int)TopLeft.X;
                    Top  = (int)TopLeft.Y;
                }

                XmlTextReader reader = new XmlTextReader(new StringReader(XmlString));
                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.Element:
                        richTextBox1.SelectionColor = BracketsColor;
                        richTextBox1.AppendText("<");
                        richTextBox1.SelectionColor = ElementNameColor;
                        richTextBox1.AppendText(reader.Name);
                        if (reader.HasAttributes)
                        {
                            for (int i = 0; i < reader.AttributeCount; i++)
                            {
                                reader.MoveToAttribute(i);
                                richTextBox1.AppendText(" ");
                                richTextBox1.SelectionColor = AttributeNameColor;
                                richTextBox1.AppendText(reader.Name);
                                richTextBox1.SelectionColor = EqualsColor;
                                richTextBox1.AppendText("=");
                                richTextBox1.SelectionColor = QuoteColor;
                                richTextBox1.AppendText("\"");
                                richTextBox1.SelectionColor = AttributeValueColor;
                                richTextBox1.AppendText(reader.Value);
                                richTextBox1.SelectionColor = QuoteColor;
                                richTextBox1.AppendText("\"");
                            }
                            reader.MoveToElement();
                        }

                        richTextBox1.SelectionColor = BracketsColor;
                        if (reader.IsEmptyElement)
                        {
                            richTextBox1.AppendText(" />");
                        }
                        else
                        {
                            richTextBox1.AppendText(">");
                        }
                        break;

                    case XmlNodeType.Text:
                        richTextBox1.SelectionColor = ElementValueColor;
                        richTextBox1.AppendText(reader.Value);
                        break;

                    case XmlNodeType.EndElement:
                        richTextBox1.SelectionColor = BracketsColor;
                        richTextBox1.AppendText("</");
                        richTextBox1.SelectionColor = ElementNameColor;
                        richTextBox1.AppendText(reader.Name);
                        richTextBox1.SelectionColor = BracketsColor;
                        richTextBox1.AppendText(">");
                        break;

                    case XmlNodeType.Whitespace:
                        richTextBox1.AppendText(reader.Value);
                        break;

                    case XmlNodeType.XmlDeclaration:
                        // Ignore this
                        break;

                    default:
                        Debug.WriteLine($"Unhandled Node is {reader.NodeType}");
                        break;
                    }
                }

                richTextBox1.SelectionStart = 0;
            }
            catch (Exception ex)
            {
                new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex).ShowDialog();
            }
        }
Exemplo n.º 36
0
        public void ParseMath(XmlTextReader reader)
        {
            switch (reader.NodeType)
            {
            case XmlNodeType.Element:
                String elementName = reader.LocalName.ToLower();

                Hashtable attributes = new Hashtable();
                if (reader.HasAttributes)
                {
                    for (int i = 0; i < reader.AttributeCount; i++)
                    {
                        reader.MoveToAttribute(i);
                        attributes.Add(reader.Name.ToLower(), reader.Value);
                    }
                }
                if (elementName == "csymbol")
                {
                    reader.Skip(); // csymbol will have an unimportant text childNode
                }

                StartMathElement(elementName, attributes);
                break;

            case XmlNodeType.EndElement:
                EndMathElement(reader.Name.ToLower());
                break;

            case XmlNodeType.Text: // from cn or ci
                MathCharacters(reader.Value);
                break;

            }
        }
        public void LoadXmlFileInTreeView(TreeView treeView, string fileName)
        {
            XmlTextReader reader = null;
            try
            {
                treeView.BeginUpdate();
                reader = new XmlTextReader(fileName);

                TreeNode n = new TreeNode(fileName);
                treeView.Nodes.Add(n);
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        bool isEmptyElement = reader.IsEmptyElement;
                        StringBuilder text = new StringBuilder();
                        text.Append(reader.Name);
                        int attributeCount = reader.AttributeCount;
                        if (attributeCount > 0)
                        {
                            text.Append(" ( ");
                            for (int i = 0; i < attributeCount; i++)
                            {
                                if (i != 0) text.Append(", ");
                                reader.MoveToAttribute(i);
                                text.Append(reader.Name);
                                text.Append(" = ");
                                text.Append(reader.Value);
                            }
                            text.Append(" ) ");
                        }

                        if (isEmptyElement)
                        {
                            n.Nodes.Add(text.ToString());
                        }
                        else
                        {
                            n = n.Nodes.Add(text.ToString());
                        }
                    }
                    else if (reader.NodeType == XmlNodeType.EndElement)
                    {
                        n = n.Parent;
                    }
                    else if (reader.NodeType == XmlNodeType.XmlDeclaration)
                    {

                    }
                    else if (reader.NodeType == XmlNodeType.None)
                    {
                        return;
                    }
                    else if (reader.NodeType == XmlNodeType.Text)
                    {
                        n.Nodes.Add(reader.Value);
                    }
                }
            }
            finally
            {
                treeView.EndUpdate();
                reader.Close();
            }
        }
        private static HTML_Based_Content Text_To_HTML_Based_Content(string Display_Text, bool Retain_Entire_Display_Text, string Source, Custom_Tracer Tracer)
        {
            // Create the values to hold the information
            string code        = String.Empty;
            string title       = String.Empty;
            string author      = String.Empty;
            string description = String.Empty;
            string thumbnail   = String.Empty;
            string keyword     = String.Empty;
            string banner      = String.Empty;
            string date        = String.Empty;
            string sitemap     = String.Empty;
            string webskin     = String.Empty;
            bool   includeMenu = false;
            string sobekControlledJavascript = String.Empty;
            string sobekControlledCss        = String.Empty;

            // StringBuilder keeps track of any other information in the head that should be retained
            StringBuilder headBuilder = new StringBuilder();

            HTML_Based_Content returnValue = new HTML_Based_Content();

            if (Tracer != null)
            {
                Tracer.Add_Trace("HTML_Based_Content_Reader.Text_To_HTML_Based_Content", "Converting source file content into object");
            }

            // Try to read the head using XML
            int head_start = Display_Text.IndexOf("<head>", StringComparison.OrdinalIgnoreCase);
            int head_end   = Display_Text.IndexOf("</head>", StringComparison.OrdinalIgnoreCase);

            if ((head_start >= 0) && (head_end > head_start))
            {
                bool read_as_xml;
                try
                {
                    if (Tracer != null)
                    {
                        Tracer.Add_Trace("HTML_Based_Content_Reader.Text_To_HTML_Based_Content", "Attempting to read the html head as XML");
                    }

                    string        head_xml  = Display_Text.Substring(head_start, (head_end - head_start) + 7);
                    XmlTextReader xmlReader = new XmlTextReader(new StringReader(head_xml));
                    while (xmlReader.Read())
                    {
                        if (xmlReader.NodeType != XmlNodeType.Element)
                        {
                            continue;
                        }

                        switch (xmlReader.Name.ToUpper())
                        {
                        case "LINK":
                            // Was this the controlled link?
                            if ((xmlReader.MoveToAttribute("id")) && (xmlReader.Value == "SobekCmControlledCss"))
                            {
                                if (xmlReader.MoveToAttribute("href"))
                                {
                                    sobekControlledCss = xmlReader.Value;
                                }
                            }
                            else
                            {
                                headBuilder.Append("<link ");
                                int attributeCount = xmlReader.AttributeCount;
                                for (int i = 0; i < attributeCount; i++)
                                {
                                    xmlReader.MoveToAttribute(i);
                                    headBuilder.Append(xmlReader.Name + "=\"" + xmlReader.Value + "\" ");
                                }
                                headBuilder.AppendLine(" />");
                            }
                            break;

                        case "SCRIPT":
                            // Was this the controlled link?
                            if ((xmlReader.MoveToAttribute("id")) && (xmlReader.Value == "SobekCmControlledJavascript"))
                            {
                                if (xmlReader.MoveToAttribute("src"))
                                {
                                    sobekControlledJavascript = xmlReader.Value;
                                }
                            }
                            else
                            {
                                headBuilder.Append("<script ");
                                int attributeCount = xmlReader.AttributeCount;
                                for (int i = 0; i < attributeCount; i++)
                                {
                                    xmlReader.MoveToAttribute(i);
                                    headBuilder.Append(xmlReader.Name + "=\"" + xmlReader.Value + "\" ");
                                }
                                headBuilder.AppendLine("></script>");
                            }
                            break;

                        case "TITLE":
                            xmlReader.Read();
                            title = xmlReader.Value;
                            break;

                        case "CODE":
                            xmlReader.Read();
                            code = xmlReader.Value.ToLower();
                            break;

                        case "META":
                            string name_type    = String.Empty;
                            string content_type = String.Empty;
                            if (xmlReader.MoveToAttribute("name"))
                            {
                                name_type = xmlReader.Value;
                            }
                            if (xmlReader.MoveToAttribute("content"))
                            {
                                content_type = xmlReader.Value;
                            }
                            if ((name_type.Length > 0) && (content_type.Length > 0))
                            {
                                switch (name_type.ToUpper())
                                {
                                case "BANNER":
                                    banner = content_type;
                                    break;

                                case "TITLE":
                                    title = content_type;
                                    break;

                                case "THUMBNAIL":
                                    thumbnail = content_type;
                                    break;

                                case "AUTHOR":
                                    author = content_type;
                                    break;

                                case "DATE":
                                    date = content_type;
                                    break;

                                case "KEYWORDS":
                                    keyword = content_type;
                                    break;

                                case "DESCRIPTION":
                                    description = content_type;
                                    break;

                                case "CODE":
                                    code = content_type.ToLower();
                                    break;

                                case "SITEMAP":
                                    sitemap = content_type;
                                    break;

                                case "WEBSKIN":
                                    webskin = content_type;
                                    break;

                                case "MENU":
                                    if (String.Compare(content_type, "true", StringComparison.OrdinalIgnoreCase) == 0)
                                    {
                                        includeMenu = true;
                                    }
                                    break;
                                }
                            }
                            break;
                        }
                    }
                    read_as_xml = true;
                }
                catch
                {
                    if (Tracer != null)
                    {
                        Tracer.Add_Trace("HTML_Based_Content_Reader.Text_To_HTML_Based_Content", "Was unable to read the html head as XML");
                    }
                    read_as_xml = false;
                }


                // Read this the old way if unable to read via XML for some reason
                if (!read_as_xml)
                {
                    if (Tracer != null)
                    {
                        Tracer.Add_Trace("HTML_Based_Content_Reader.Text_To_HTML_Based_Content", "Attempting to parse html head for title, code, and banner information");
                    }

                    // Get the title and code
                    string header_info = Display_Text.Substring(0, Display_Text.IndexOf("<body>"));
                    if (header_info.IndexOf("<title>") > 0)
                    {
                        string possible_title = header_info.Substring(header_info.IndexOf("<title>"));
                        possible_title = possible_title.Substring(7, possible_title.IndexOf("</title>") - 7);
                        title          = possible_title.Trim();
                    }
                    if (header_info.IndexOf("<code>") > 0)
                    {
                        string possible_code = header_info.Substring(header_info.IndexOf("<code>"));
                        possible_code = possible_code.Substring(6, possible_code.IndexOf("</code>") - 6);
                        code          = possible_code.Trim();
                    }

                    // See if the banner should be displayed (default is only option righht now)
                    if (Display_Text.IndexOf("<meta name=\"banner\" content=\"default\"") > 0)
                    {
                        banner = "default";
                    }
                }

                // Create return value
                if (code.Length > 0)
                {
                    returnValue.Code = code;
                }
                if (title.Length > 0)
                {
                    returnValue.Title = title;
                }
                if (author.Length > 0)
                {
                    returnValue.Author = author;
                }
                if (banner.Length > 0)
                {
                    returnValue.Banner = banner;
                }
                if (date.Length > 0)
                {
                    returnValue.Date = date;
                }
                if (description.Length > 0)
                {
                    returnValue.Description = description;
                }
                if (keyword.Length > 0)
                {
                    returnValue.Keywords = keyword;
                }
                if (thumbnail.Length > 0)
                {
                    returnValue.Thumbnail = thumbnail;
                }
                if (sitemap.Length > 0)
                {
                    returnValue.SiteMap = sitemap;
                }
                if (webskin.Length > 0)
                {
                    returnValue.Web_Skin = webskin;
                }
                if (headBuilder.Length > 0)
                {
                    returnValue.Extra_Head_Info = headBuilder.ToString();
                }
                if (includeMenu)
                {
                    returnValue.IncludeMenu = true;
                }
                if (sobekControlledCss.Length > 0)
                {
                    returnValue.CssFile = sobekControlledCss;
                }
                if (sobekControlledJavascript.Length > 0)
                {
                    returnValue.JavascriptFile = sobekControlledJavascript;
                }
            }
            else
            {
                if (Tracer != null)
                {
                    Tracer.Add_Trace("HTML_Based_Content_Reader.Text_To_HTML_Based_Content", "No html head found in source file");
                }
            }

            // Should the actual display text be retained?
            if (Retain_Entire_Display_Text)
            {
                if (Tracer != null)
                {
                    Tracer.Add_Trace("HTML_Based_Content_Reader.Text_To_HTML_Based_Content", "Reading the entire display text and saving in the object");
                }

                int start_body = Display_Text.IndexOf("<body>");
                int end_body   = Display_Text.IndexOf("</body>");
                if ((start_body > 0) && (end_body > start_body))
                {
                    start_body         += 6;
                    returnValue.Content = Display_Text.Substring(start_body, end_body - start_body) + " ";

                    if ((Source.Length > 0) && (returnValue.Content.IndexOf("<%LASTMODIFIED%>") > 0))
                    {
                        FileInfo fileInfo    = new FileInfo(Source);
                        DateTime lastWritten = fileInfo.LastWriteTime;
                        returnValue.Content = returnValue.Content.Replace("<%LASTMODIFIED%>", lastWritten.ToLongDateString());
                    }
                }
                else
                {
                    returnValue.Content = Display_Text.Replace("<body>", "").Replace("</body>", "");
                }
            }

            return(returnValue);
        }
Exemplo n.º 39
0
        public static void PrettyPrint(string xmlData, out string prettyXml, XmlHighlighter highlighter)
        {
            StringReader  stringReader = new StringReader(xmlData);
            XmlTextReader reader       = new XmlTextReader(stringReader);
            StringBuilder builder      = new StringBuilder(xmlData.Length);

            string[] tokens;
            char[]   nsSepChars = new char[] { ':' };

            int indent = 0;

            while (reader.Read())
            {
                int offset;

                switch (reader.NodeType)
                {
                case XmlNodeType.Element:
                    builder.AppendFormat("{0,-" + Convert.ToString(indent) + "}", "");

                    offset = builder.Length;
                    builder.Append("<");
                    if (highlighter != null)
                    {
                        highlighter.AddToken(XmlHighlightContext.ELEMENT_OPENING, offset, builder.Length - offset);
                    }

                    offset = builder.Length;
                    tokens = reader.Name.Split(nsSepChars, 2);
                    if (tokens.Length > 1)
                    {
                        builder.Append(tokens[0]);
                        if (highlighter != null)
                        {
                            highlighter.AddToken(XmlHighlightContext.ELEMENT_NAMESPACE_NAME, offset, builder.Length - offset);
                        }

                        offset = builder.Length;
                        builder.Append(":");
                        if (highlighter != null)
                        {
                            highlighter.AddToken(XmlHighlightContext.ELEMENT_NAMESPACE_SEPARATOR, offset, 1);
                        }

                        offset = builder.Length;
                        builder.Append(tokens[1]);
                    }
                    else
                    {
                        builder.Append(tokens[0]);
                    }

                    if (highlighter != null)
                    {
                        highlighter.AddToken(XmlHighlightContext.ELEMENT_NAME, offset, builder.Length - offset);
                    }

                    bool empty;
                    empty = reader.IsEmptyElement;

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

                        builder.Append(" ");

                        offset = builder.Length;

                        offset = builder.Length;
                        tokens = reader.Name.Split(nsSepChars, 2);
                        if (tokens.Length > 1)
                        {
                            builder.Append(tokens[0]);
                            if (highlighter != null)
                            {
                                highlighter.AddToken(XmlHighlightContext.ELEMENT_ATTRIBUTE_KEY, offset, builder.Length - offset);
                            }

                            offset = builder.Length;
                            builder.Append(":");
                            if (highlighter != null)
                            {
                                highlighter.AddToken(XmlHighlightContext.ELEMENT_NAMESPACE_SEPARATOR, offset, 1);
                            }

                            offset = builder.Length;
                            builder.Append(tokens[1]);
                        }
                        else
                        {
                            builder.Append(tokens[0]);
                        }

                        if (highlighter != null)
                        {
                            highlighter.AddToken(XmlHighlightContext.ELEMENT_ATTRIBUTE_KEY, offset, builder.Length - offset);
                        }

                        builder.Append("=\"");

                        offset = builder.Length;
                        builder.Append(reader.Value);
                        if (highlighter != null)
                        {
                            highlighter.AddToken(XmlHighlightContext.ELEMENT_ATTRIBUTE_VALUE, offset, builder.Length - offset);
                        }

                        builder.Append("\"");
                    }

                    offset = builder.Length;

                    if (empty)
                    {
                        builder.Append("/");
                    }
                    else
                    {
                        indent += 4;
                    }

                    builder.Append(">");
                    if (highlighter != null)
                    {
                        highlighter.AddToken(XmlHighlightContext.ELEMENT_CLOSING, offset, builder.Length - offset);
                    }

                    builder.Append("\n");

                    break;

                case XmlNodeType.EndElement:
                    indent -= 4;

                    builder.AppendFormat("{0,-" + Convert.ToString(indent) + "}", "");

                    offset = builder.Length;
                    builder.Append("</");
                    if (highlighter != null)
                    {
                        highlighter.AddToken(XmlHighlightContext.ELEMENT_OPENING, offset, builder.Length - offset);
                    }

                    offset = builder.Length;
                    tokens = reader.Name.Split(nsSepChars, 2);
                    if (tokens.Length > 1)
                    {
                        builder.Append(tokens[0]);
                        if (highlighter != null)
                        {
                            highlighter.AddToken(XmlHighlightContext.ELEMENT_NAMESPACE_NAME, offset, builder.Length - offset);
                        }

                        offset = builder.Length;
                        builder.Append(":");
                        if (highlighter != null)
                        {
                            highlighter.AddToken(XmlHighlightContext.ELEMENT_NAMESPACE_SEPARATOR, offset, 1);
                        }

                        offset = builder.Length;
                        builder.Append(tokens[1]);
                    }
                    else
                    {
                        builder.Append(tokens[0]);
                    }

                    if (highlighter != null)
                    {
                        highlighter.AddToken(XmlHighlightContext.ELEMENT_NAME, offset, builder.Length - offset);
                    }

                    offset = builder.Length;
                    builder.Append(">");
                    if (highlighter != null)
                    {
                        highlighter.AddToken(XmlHighlightContext.ELEMENT_CLOSING, offset, builder.Length - offset);
                    }

                    builder.Append("\n");
                    break;

                case XmlNodeType.Text:
                    builder.AppendFormat("{0,-" + Convert.ToString(indent) + "}", "");
                    builder.Append(reader.Value);
                    builder.Append("\n");
                    break;
                }
            }

            prettyXml = builder.ToString().TrimEnd(new char[] { '\n' });
        }
        public void DeserializeTreeView(TreeView treeView, string fileName)
        {
            XmlTextReader reader = null;
            try
            {
                // disabling re-drawing of treeview till all nodes are added
                treeView.BeginUpdate();
                reader = new XmlTextReader(fileName);

                TreeNode parentNode = null;

                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        if (reader.Name == XmlNodeTag)
                        {
                            TreeNode newNode = new TreeNode();
                            bool isEmptyElement = reader.IsEmptyElement;

                            // loading node attributes
                            int attributeCount = reader.AttributeCount;
                            if (attributeCount > 0)
                            {
                                for (int i = 0; i < attributeCount; i++)
                                {
                                    reader.MoveToAttribute(i);
                                    SetAttributeValue(newNode, reader.Name, reader.Value);
                                }
                            }

                            // add new node to Parent Node or TreeView
                            if (parentNode != null)
                                parentNode.Nodes.Add(newNode);
                            else
                                treeView.Nodes.Add(newNode);

                            // making current node 'ParentNode' if its not empty
                            if (!isEmptyElement)
                            {
                                parentNode = newNode;
                            }
                        }
                    }
                    // moving up to in TreeView if end tag is encountered
                    else if (reader.NodeType == XmlNodeType.EndElement)
                    {
                        if (reader.Name == XmlNodeTag)
                        {
                            parentNode = parentNode.Parent;
                        }
                    }
                    else if (reader.NodeType == XmlNodeType.XmlDeclaration)
                    { //Ignore Xml Declaration
                    }
                    else if (reader.NodeType == XmlNodeType.None)
                    {
                        return;
                    }
                    else if (reader.NodeType == XmlNodeType.Text)
                    {
                        parentNode.Nodes.Add(reader.Value);
                    }
                }
            }
            finally
            {
                // enabling redrawing of treeview after all nodes are added
                treeView.EndUpdate();
                reader.Close();
            }
        }
Exemplo n.º 41
0
        public static void StartTrace(CollectorParameters Collector)
        {
            void RetargetEventSource(String LegacySource)
            {
                // This is a fix for: https://github.com/fireeye/SilkETW/issues/4
                // When both SilkETW and SilkService are used on the same host
                // eventlog logging would fail for one or the other as they had
                // the same source. This function will retarget the source.
                if (EventLog.SourceExists(LegacySource))
                {
                    EventLog.DeleteEventSource(LegacySource);
                }
            }

            Boolean WriteEventLogEntry(String Message, EventLogEntryType Type, EventIds EventId, String Path)
            {
                //--[Event ID's]
                // 0 == Collector start
                // 1 == Collector terminated -> by user
                // 2 == Collector terminated -> by error
                // 3 == Event recorded
                //--

                try
                {
                    // Fix legacy collector source
                    RetargetEventSource("ETW Collector");

                    // Event log properties
                    String Source = "SilkService Collector";

                    // If the source doesn't exist we have to create it first
                    if (!EventLog.SourceExists(Source))
                    {
                        EventLog.CreateEventSource(Source, Path);
                    }

                    // Write event
                    using (EventLog Log = new EventLog(Path))
                    {
                        Log.Source           = Source;
                        Log.MaximumKilobytes = 99968;                                   // Max ~100mb size -> needs 64kb increments
                        Log.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded, 10); // Always overwrite oldest
                        Log.WriteEntry(Message, Type, (int)EventId);
                    }
                    return(true);
                }
                catch
                {
                    return(false);
                }
            }

            int ProcessJSONEventData(String JSONData, OutputType OutputType, String Path, String YaraScan, YaraOptions YaraOptions, YSInstance YaraInstance, YSRules YaraRules)
            {
                // Yara matches
                List <String> YaraRuleMatches = new List <String>();

                // Yara options
                if (YaraScan != String.Empty)
                {
                    byte[]           JSONByteArray = Encoding.ASCII.GetBytes(JSONData);
                    List <YSMatches> Matches       = YaraInstance.ScanMemory(JSONByteArray, YaraRules, null, 0);
                    YaraRuleMatches.Clear();
                    if (Matches.Count != 0)
                    {
                        foreach (YSMatches Match in Matches)
                        {
                            YaraRuleMatches.Add(Match.Rule.Identifier);
                        }

                        // Dynamically update the JSON object -> List<String> YaraRuleMatches
                        JObject obj = JObject.Parse(JSONData);
                        ((JArray)obj["YaraMatch"]).Add(YaraRuleMatches);
                        JSONData = obj.ToString(Newtonsoft.Json.Formatting.None);
                    }
                }

                if (YaraOptions == YaraOptions.All || YaraOptions == YaraOptions.None || (YaraScan != String.Empty && YaraRuleMatches.Count > 0))
                {
                    //--[Return Codes]
                    // 0 == OK
                    // 1 == File write failed
                    // 2 == URL POST request failed
                    // 3 == Eventlog write failed
                    //--

                    // Process JSON
                    if (OutputType == OutputType.file)
                    {
                        try
                        {
                            if (!File.Exists(Path))
                            {
                                File.WriteAllText(Path, (JSONData + Environment.NewLine));
                            }
                            else
                            {
                                File.AppendAllText(Path, (JSONData + Environment.NewLine));
                            }

                            return(0);
                        }
                        catch
                        {
                            return(1);
                        }
                    }
                    else if (OutputType == OutputType.url)
                    {
                        try
                        {
                            string         responseFromServer = string.Empty;
                            HttpWebRequest webRequest         = (HttpWebRequest)WebRequest.Create(Path);
                            webRequest.Timeout     = 10000; // 10 second timeout
                            webRequest.Method      = "POST";
                            webRequest.ContentType = "application/json";
                            webRequest.Accept      = "application/json";
                            using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
                            {
                                streamWriter.Write(JSONData);
                                streamWriter.Flush();
                                streamWriter.Close();
                            }
                            var httpResponse = (HttpWebResponse)webRequest.GetResponse();
                            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                            {
                                var result = streamReader.ReadToEnd();
                            }

                            return(0);
                        }
                        catch
                        {
                            return(2);
                        }
                    }
                    else
                    {
                        Boolean WriteEvent = WriteEventLogEntry(JSONData, EventLogEntryType.Information, EventIds.Event, Path);

                        if (WriteEvent)
                        {
                            return(0);
                        }
                        else
                        {
                            return(3);
                        }
                    }
                }
                else
                {
                    return(0);
                }
            }

            // Local variables for StartTrace
            String  EventParseSessionName;
            Boolean ProcessEventData;

            // Is elevated? While running as a service this should always be true but
            // this is kept for edge-case user-fail.
            if (TraceEventSession.IsElevated() != true)
            {
                SilkUtility.WriteCollectorGuidMessageToServiceTextLog(Collector.CollectorGUID, "The collector must be run elevated", true);
                return;
            }

            // Print status
            SilkUtility.WriteCollectorGuidMessageToServiceTextLog(Collector.CollectorGUID, "Starting trace collector", false);

            // We tag event sessions with a unique name
            // While running these are observable with => logman -ets
            if (Collector.CollectorType == CollectorType.Kernel)
            {
                EventParseSessionName = KernelTraceEventParser.KernelSessionName;
            }
            else
            {
                String RandId = Guid.NewGuid().ToString();
                EventParseSessionName = ("SilkServiceUserCollector_" + RandId);
            }

            // Create trace session
            using (var TraceSession = new TraceEventSession(EventParseSessionName))
            {
                // The collector cannot survive process termination (safeguard)
                TraceSession.StopOnDispose = true;

                // Create event source
                using (var EventSource = new ETWTraceEventSource(EventParseSessionName, TraceEventSourceType.Session))
                {
                    // A DynamicTraceEventParser can understand how to read the embedded manifests that occur in the dataStream
                    var EventParser = new DynamicTraceEventParser(EventSource);

                    // Loop events as they arrive
                    EventParser.All += delegate(TraceEvent data)
                    {
                        // It's a bit ugly but ... ¯\_(ツ)_/¯
                        if (Collector.FilterOption != FilterOption.None)
                        {
                            if (Collector.FilterOption == FilterOption.Opcode && (byte)data.Opcode != (byte)Collector.FilterValue)
                            {
                                ProcessEventData = false;
                            }
                            else if (Collector.FilterOption == FilterOption.ProcessID && data.ProcessID != (UInt32)Collector.FilterValue)
                            {
                                ProcessEventData = false;
                            }
                            else if (Collector.FilterOption == FilterOption.ProcessName && data.ProcessName != (String)Collector.FilterValue)
                            {
                                ProcessEventData = false;
                            }
                            else if (Collector.FilterOption == FilterOption.EventName && data.EventName != (String)Collector.FilterValue)
                            {
                                ProcessEventData = false;
                            }
                            else
                            {
                                ProcessEventData = true;
                            }
                        }
                        else
                        {
                            ProcessEventData = true;
                        }

                        // Only process/serialize events if they match our filter
                        if (ProcessEventData)
                        {
                            var eRecord = new EventRecordStruct
                            {
                                ProviderGuid    = data.ProviderGuid,
                                YaraMatch       = new List <String>(),
                                ProviderName    = data.ProviderName,
                                EventName       = data.EventName,
                                Opcode          = data.Opcode,
                                OpcodeName      = data.OpcodeName,
                                TimeStamp       = data.TimeStamp,
                                ThreadID        = data.ThreadID,
                                ProcessID       = data.ProcessID,
                                ProcessName     = data.ProcessName,
                                PointerSize     = data.PointerSize,
                                EventDataLength = data.EventDataLength
                            };

                            // Populate Proc name if undefined
                            if (String.IsNullOrEmpty(eRecord.ProcessName))
                            {
                                try
                                {
                                    eRecord.ProcessName = Process.GetProcessById(eRecord.ProcessID).ProcessName;
                                }
                                catch
                                {
                                    eRecord.ProcessName = "N/A";
                                }
                            }
                            var EventProperties = new Hashtable();

                            // Try to parse event XML
                            try
                            {
                                StringReader  XmlStringContent   = new StringReader(data.ToString());
                                XmlTextReader EventElementReader = new XmlTextReader(XmlStringContent);
                                while (EventElementReader.Read())
                                {
                                    for (int AttribIndex = 0; AttribIndex < EventElementReader.AttributeCount; AttribIndex++)
                                    {
                                        EventElementReader.MoveToAttribute(AttribIndex);

                                        // Cap maxlen for eventdata elements to 10k
                                        if (EventElementReader.Value.Length > 10000)
                                        {
                                            String DataValue = EventElementReader.Value.Substring(0, Math.Min(EventElementReader.Value.Length, 10000));
                                            EventProperties.Add(EventElementReader.Name, DataValue);
                                        }
                                        else
                                        {
                                            EventProperties.Add(EventElementReader.Name, EventElementReader.Value);
                                        }
                                    }
                                }
                            }
                            catch
                            {
                                // For debugging (?), never seen this fail
                                EventProperties.Add("XmlEventParsing", "false");
                            }
                            eRecord.XmlEventData = EventProperties;

                            // Serialize to JSON
                            String JSONEventData = Newtonsoft.Json.JsonConvert.SerializeObject(eRecord);
                            int    ProcessResult = ProcessJSONEventData(JSONEventData, Collector.OutputType, Collector.Path, Collector.YaraScan, Collector.YaraOptions, Collector.YaraInstance, Collector.YaraRules);

                            // Verify that we processed the result successfully
                            if (ProcessResult != 0)
                            {
                                if (ProcessResult == 1)
                                {
                                    SilkUtility.WriteCollectorGuidMessageToServiceTextLog(Collector.CollectorGUID, "The collector failed to write to file", true);
                                }
                                else if (ProcessResult == 2)
                                {
                                    SilkUtility.WriteCollectorGuidMessageToServiceTextLog(Collector.CollectorGUID, "The collector failed to POST the result", true);
                                }
                                else
                                {
                                    SilkUtility.WriteCollectorGuidMessageToServiceTextLog(Collector.CollectorGUID, "The collector failed write to the eventlog", true);
                                }

                                // Write status to eventlog if dictated by the output type
                                if (Collector.OutputType == OutputType.eventlog)
                                {
                                    WriteEventLogEntry($"{{\"Collector\":\"Stop\",\"Error\":true,\"ErrorCode\":{ProcessResult}}}", EventLogEntryType.Error, EventIds.StopError, Collector.Path);
                                }

                                // This collector encountered an error, terminate the service
                                TerminateCollector();
                            }
                        }
                    };

                    // Specify the providers details
                    if (Collector.CollectorType == CollectorType.Kernel)
                    {
                        TraceSession.EnableKernelProvider((KernelTraceEventParser.Keywords)Collector.KernelKeywords);
                    }
                    else
                    {
                        // Note that the collector doesn't know if you specified a wrong provider name,
                        // the only tell is that you won't get any events ;)
                        TraceSession.EnableProvider(Collector.ProviderName, (TraceEventLevel)Collector.UserTraceEventLevel, (ulong)Collector.UserKeywords);
                    }

                    // Write status to eventlog if dictated by the output type
                    if (Collector.OutputType == OutputType.eventlog)
                    {
                        String ConvertKeywords;
                        if (Collector.CollectorType == CollectorType.Kernel)
                        {
                            ConvertKeywords = Enum.GetName(typeof(KernelTraceEventParser.Keywords), Collector.KernelKeywords);
                        }
                        else
                        {
                            ConvertKeywords = "0x" + String.Format("{0:X}", (ulong)Collector.UserKeywords);
                        }
                        String Message = $"{{\"Collector\":\"Start\",\"Data\":{{\"Type\":\"{Collector.CollectorType}\",\"Provider\":\"{Collector.ProviderName}\",\"Keywords\":\"{ConvertKeywords}\",\"FilterOption\":\"{Collector.FilterOption}\",\"FilterValue\":\"{Collector.FilterValue}\",\"YaraPath\":\"{Collector.YaraScan}\",\"YaraOption\":\"{Collector.YaraOptions}\"}}}}";
                        WriteEventLogEntry(Message, EventLogEntryType.SuccessAudit, EventIds.Start, Collector.Path);
                    }

                    // Populate the trace bookkeeper
                    var CollectorInstance = new CollectorInstance
                    {
                        CollectorGUID         = Collector.CollectorGUID,
                        EventSource           = EventSource,
                        EventParseSessionName = EventParseSessionName,
                    };
                    SilkUtility.CollectorTaskList.Add(CollectorInstance);

                    // Signal the ManualResetEvent
                    SilkUtility.SignalThreadStarted.Set();

                    // Continuously process all new events in the data source
                    EventSource.Process();

                    void TerminateCollector()
                    {
                        EventSource.StopProcessing();
                        TraceSession?.Stop();
                        SilkUtility.WriteCollectorGuidMessageToServiceTextLog(Collector.CollectorGUID, "Collector terminated", false);
                        return;
                    }
                }
            }
        }
Exemplo n.º 42
0
    /// <summary>
    /// Reads through the XML file and adds the new
    /// exchange rates to the list.
    /// </summary>
    private static void AddCurrency(Dictionary<string, double> currencies, XmlTextReader xmlReader)
    {
        if (xmlReader.Name == "Cube")
        {
          if (xmlReader.AttributeCount == 1)
          {
        xmlReader.MoveToAttribute("time");
        _LastUpdated = DateTime.Parse(xmlReader.Value);
          }

          if (xmlReader.AttributeCount == 2)
          {
        xmlReader.MoveToAttribute("currency");
        string name = xmlReader.Value;

        xmlReader.MoveToAttribute("rate");
        //double rate = double.Parse(xmlReader.Value.Replace(".", ","));
        double rate = double.Parse(xmlReader.Value);

        currencies.Add(name, rate);
          }
        }
    }
Exemplo n.º 43
0
        public static Stream Format(Stream input)
        {
            int t1 = Environment.TickCount;

            var r = new XmlTextReader(input)
            {
                DtdProcessing      = DtdProcessing.Ignore,
                WhitespaceHandling = WhitespaceHandling.None
            };
            XmlNamespaceManager nsmgr = XmlNamespaces.GetNamespaceManager(r.NameTable);

            var m = new MemoryStream();
            var w = new XmlTextWriter(m, Encoding.UTF8)
            {
                Formatting  = Formatting.Indented,
                Indentation = 2
            };

            w.WriteStartDocument();

            while (r.Read())
            {
                switch (r.NodeType)
                {
                case XmlNodeType.Element:
                    w.WriteStartElement(r.Prefix, r.LocalName, r.NamespaceURI);
                    if (r.HasAttributes)
                    {
                        string elementQName = XmlUtil.GetQName(r, nsmgr);
                        for (int i = 0; i < r.AttributeCount; ++i)
                        {
                            r.MoveToAttribute(i);
                            string attributeQName = XmlUtil.GetQName(r, nsmgr);
                            string xpath          = elementQName + "/@" + attributeQName;
                            // Filter out language="*"
                            if ((xpath.Equals(XPaths.languageAttribute1, StringComparison.Ordinal) || xpath.Equals(
                                     XPaths.languageAttribute2,
                                     StringComparison.Ordinal)) && String.Equals(
                                    r.Value,
                                    "*",
                                    StringComparison.Ordinal))
                            {
                                continue;
                            }
                            // Filter out attributes with empty values if attribute is on the list...
                            if (String.IsNullOrEmpty(r.Value) &&
                                Array.BinarySearch(XPaths.emptyAttributeList, xpath) >= 0)
                            {
                                continue;
                            }
                            w.WriteAttributeString(r.Prefix, r.LocalName, r.NamespaceURI, r.Value);
                        }

                        r.MoveToElement();     // Moves the reader back to the element node.
                    }

                    if (r.IsEmptyElement)
                    {
                        w.WriteEndElement();
                    }

                    break;

                case XmlNodeType.EndElement:
                    w.WriteEndElement();
                    break;

                case XmlNodeType.Comment:
                    w.WriteComment(r.Value);
                    break;

                case XmlNodeType.CDATA:
                    w.WriteCData(r.Value);
                    break;

                case XmlNodeType.Text:
                    w.WriteString(r.Value);
                    break;
                }
            }

            w.WriteEndDocument();
            w.Flush();
            m.Position = 0;
            Util.WriteLog(String.Format(CultureInfo.CurrentCulture, "ManifestWriter.Format t={0}", Environment.TickCount - t1));
            return(m);
        }