internal XDeclaration(XmlReader r) { _version = r.GetAttribute("version"); _encoding = r.GetAttribute("encoding"); _standalone = r.GetAttribute("standalone"); r.Read(); }
internal XDocumentType(XmlReader r) { _name = r.Name; _publicId = r.GetAttribute("PUBLIC"); _systemId = r.GetAttribute("SYSTEM"); _internalSubset = r.Value; r.Read(); }
public void LoadXML(XmlReader r) { Name=r.GetAttribute ("Name"); IP=r.GetAttribute ("IP"); Location=r.GetAttribute ("Location"); string v=r.GetAttribute ("Longitude"); if (v != null && v != "") lng = double.Parse (v); v=r.GetAttribute ("Latitude"); if (v != null && v != "") lat = double.Parse (v); }
/* //http://docs.opencv.org/doc/tutorials/calib3d/camera_calibration/camera_calibration.html public float fov=60; //horizontal field of view for the camera measured in degrees public float cameraOffset=0; //physical offset from human eye public float stereoOffset=0.065f; //physical distance between both eyes public ECameraRotation[] cameraRotation=new ECameraRotation[2]; public Vector2 OpticalCenter=new Vector2(0.5f,0.5f); public Vector2 FocalCoeff=new Vector2(1,1); public Vector4 KPCoeff=Vector4.zero; public string Name="";*/ public void LoadXML(XmlReader r) { Name=r.GetAttribute ("Name"); float.TryParse( r.GetAttribute ("FOV"),out FoV); float.TryParse( r.GetAttribute ("CameraOffset"),out CameraOffset); LensCenter=Utilities.ParseVector2( r.GetAttribute ("OpticalCenter")); FocalLength=Utilities.ParseVector2( r.GetAttribute ("FocalCoeff")); KPCoeff=Utilities.ParseVector4( r.GetAttribute ("KPCoeff")); Vector4 PixelShift=Utilities.ParseVector4( r.GetAttribute ("PixelShift")); PixelShiftLeft.Set (PixelShift.x, PixelShift.y); PixelShiftRight.Set (PixelShift.z, PixelShift.w); string rot; string[] names = new string[]{"LeftRotation","RightRotation"}; for (int i=0; i<2; ++i) { rot = r.GetAttribute (names[i]).ToLower (); switch (rot) { case "none": Rotation[i]=ECameraRotation.None; break; case "flipped": Rotation[i]=ECameraRotation.Flipped; break; case "cw": Rotation[i]=ECameraRotation.CW; break; case "ccw": Rotation[i]=ECameraRotation.CCW; break; } } }
public static BaseNode GetNodeFromClassName(XmlReader reader) { BaseNode result = null; string className = reader?.GetAttribute("Class"); if (!string.IsNullOrEmpty(className)) { result = GetNodeFromClassName(className); } return(result); }
public static QuestionGenerator CreateGeneratorFromXml(XmlReader reader) { bool used = reader.GetAttribute("Used").Equals("y"); if(!used) return null; QuestionGenerator generator = new QuestionGenerator(); generator.m_tags = reader.GetAttribute("Tags").Split(';'); generator.m_type = (GeneratorType)System.Enum.Parse(typeof(GeneratorType), reader.GetAttribute("Type")); generator.m_weight = System.Convert.ToSingle(reader.GetAttribute("Weight")); generator.m_questionText = reader.GetAttribute("QuestionText"); generator.m_adjacentWithin = System.Convert.ToInt32(reader.GetAttribute("AdjacentWithin")); generator.m_infoPrefix = reader.GetAttribute("InfoPrefix"); generator.m_infoSuffix = reader.GetAttribute("InfoSuffix"); bool preventDuplicates = generator.m_type == GeneratorType.SortedMultiset; reader.ReadToDescendant("Answer"); do{ generator.AddAnswer(reader.GetAttribute("Text"), reader.GetAttribute("Value"), preventDuplicates); }while(reader.ReadToNextSibling("Answer")); return generator; }
public override void gaxb_final(XmlReader reader, object _parent, Hashtable args) { base.gaxb_final(reader, _parent, args); string attrib; if (reader != null) { attrib = reader.GetAttribute ("resourcePath"); if (attrib != null) { resourcePath = attrib; } attrib = reader.GetAttribute ("onFinished"); if (attrib != null) { onFinished = attrib; } attrib = reader.GetAttribute ("loops"); if (attrib != null) { loops = bool.Parse (attrib); } } }
public override void gaxb_final(XmlReader reader, object _parent, Hashtable args) { base.gaxb_final (reader, _parent, args); string attrib; if (reader != null) { attrib = reader.GetAttribute ("regexValidation"); if (attrib != null) { regexValidation = attrib; } } ScheduleForStart (); ScheduleForUpdate (); }
public override void gaxb_load(XmlReader reader, object _parent, Hashtable args) { base.gaxb_load(reader, _parent, args); if(reader == null && _parent == null) return; parent = _parent; if(this.GetType() == typeof( PUCanvas )) { gaxb_addToParent(); } //xmlns = reader.GetAttribute("xmlns"); string attr; attr = reader.GetAttribute("renderMode"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr == null) { attr = "ScreenSpaceOverlay"; } if(attr != null) { renderMode = (PlanetUnity2.CanvasRenderMode)Enum.Parse(typeof(PlanetUnity2.CanvasRenderMode), attr); } attr = reader.GetAttribute("pixelPerfect"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr == null) { attr = "false"; } if(attr != null) { pixelPerfect = bool.Parse(attr); } }
/// <summary> /// Parse a Logiqx XML DAT and return all found games and roms within /// </summary> /// <param name="filename">Name of the file to be parsed</param> /// <param name="indexId">Index ID for the DAT</param> /// <param name="keep">True if full pathnames are to be kept, false otherwise (default)</param> /// <param name="throwOnError">True if the error that is thrown should be thrown back to the caller, false otherwise</param> protected override void ParseFile(string filename, int indexId, bool keep, bool throwOnError = false) { // Prepare all internal variables XmlReader xtr = filename.GetXmlTextReader(); List <string> dirs = new List <string>(); // If we got a null reader, just return if (xtr == null) { return; } // Otherwise, read the file to the end try { xtr.MoveToContent(); while (!xtr.EOF) { // We only want elements if (xtr.NodeType != XmlNodeType.Element) { // If we're ending a dir, remove the last item from the dirs list, if possible if (xtr.Name == "dir" && dirs.Count > 0) { dirs.RemoveAt(dirs.Count - 1); } xtr.Read(); continue; } switch (xtr.Name) { // The datafile tag can have some attributes case "datafile": Header.Build = Header.Build ?? xtr.GetAttribute("build"); Header.Debug = Header.Debug ?? xtr.GetAttribute("debug").AsYesNo(); xtr.Read(); break; // We want to process the entire subtree of the header case "header": ReadHeader(xtr.ReadSubtree(), keep); // Skip the header node now that we've processed it xtr.Skip(); break; // Unique to RomVault-created DATs case "dir": Header.Type = "SuperDAT"; dirs.Add(xtr.GetAttribute("name") ?? string.Empty); xtr.Read(); break; // We want to process the entire subtree of the game case "machine": // New-style Logiqx case "game": // Old-style Logiqx ReadMachine(xtr.ReadSubtree(), dirs, filename, indexId, keep); // Skip the machine now that we've processed it xtr.Skip(); break; default: xtr.Read(); break; } } } catch (Exception ex) { logger.Warning(ex, $"Exception found while parsing '{filename}'"); if (throwOnError) { xtr.Dispose(); throw ex; } // For XML errors, just skip the affected node xtr?.Read(); } xtr.Dispose(); }
// Read and extract into InterfaceRight class each attribut of node name "group" InterfaceElement check_attribute_group(XmlReader xml_reader) { InterfaceElement s_InterfaceElement = new InterfaceElement(); s_InterfaceElement.mse_type = 0; s_InterfaceElement.b_toggle_type = false; s_InterfaceElement.s_content = "undefined"; s_InterfaceElement.s_text_area = "Choose a title"; if (xml_reader.HasAttributes) { while (xml_reader.MoveToNextAttribute() != false) { bool valide_type = true; string save_type = ""; string save_readstring = ""; string save_content = ""; // if type exist, else, a button will be created if ((save_type = xml_reader.GetAttribute("type")) != null) { if (Enum.IsDefined(typeof(me_button_type),save_type) == true) s_InterfaceElement.mse_type = (me_button_type)Enum.Parse(typeof(me_button_type), save_type); else valide_type = false; } // if content as attribute or string exist, else, "undefined" has been saved if ((save_content = xml_reader.GetAttribute("content")) != null || (save_readstring = xml_reader.ReadString()) != null) { s_InterfaceElement.s_content = save_content != null ? save_content : save_readstring; if (valide_type == false) s_InterfaceElement.s_content += " (Coming Soon)"; } } } return s_InterfaceElement; }
public override void gaxb_load(XmlReader reader, object _parent, Hashtable args) { base.gaxb_load(reader, _parent, args); if(reader == null && _parent == null) return; parent = _parent; if(this.GetType() == typeof( PUSwitcher )) { gaxb_addToParent(); } //xmlns = reader.GetAttribute("xmlns"); string attr; attr = reader.GetAttribute("currentIndex"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr == null) { attr = "0"; } if(attr != null) { currentIndex = (int)float.Parse(attr); } }
private void ComputeFieldInfo(DynamicTraceEventData template, XmlReader reader) { List<string> payloadNames = new List<string>(); List<DynamicTraceEventData.PayloadFetch> payloadFetches = new List<DynamicTraceEventData.PayloadFetch>(); short offset = 0; while (reader.Read()) { if (reader.Name == "data") { Type type = GetTypeForManifestTypeName(reader.GetAttribute("inType")); short size = DynamicTraceEventData.SizeOfType(type); // TODO There is disagreement in what win:Boolean means. Currently it is serialized as 1 byte // by manage code. However all other windows tools assume it is 4 bytes. we are likely // to change this to align with windows at some point. payloadNames.Add(reader.GetAttribute("name")); payloadFetches.Add(new DynamicTraceEventData.PayloadFetch(offset, size, type)); if (offset >= 0) { Debug.Assert(size != 0); if (size >= 0) offset += size; else offset = short.MinValue; } } } template.payloadNames = payloadNames.ToArray(); template.payloadFetches = payloadFetches.ToArray(); }
public override void gaxb_load(XmlReader reader, object _parent, Hashtable args) { base.gaxb_load(reader, _parent, args); if(reader == null && _parent == null) return; parent = _parent; if(this.GetType() == typeof( PUAspectFit )) { gaxb_addToParent(); } xmlns = reader.GetAttribute("xmlns"); string attr; attr = reader.GetAttribute("contentSize"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr == null) { attr = "0,0"; } if(attr != null) { contentSize = new Vector2().PUParse(attr); } attr = reader.GetAttribute("mode"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr == null) { attr = "FitInParent"; } if(attr != null) { mode = (PlanetUnity2.AspectFitMode)Enum.Parse(typeof(PlanetUnity2.AspectFitMode), attr); } }
/// <summary> /// Read game/machine information /// </summary> /// <param name="reader">XmlReader to use to parse the machine</param> /// <param name="dirs">List of dirs to prepend to the game name</param> /// <param name="filename">Name of the file to be parsed</param> /// <param name="indexId">Index ID for the DAT</param> /// <param name="keep">True if full pathnames are to be kept, false otherwise (default)</param> private void ReadMachine( XmlReader reader, List <string> dirs, // Standard Dat parsing string filename, int indexId, // Miscellaneous bool keep) { // If we have an empty machine, skip it if (reader == null) { return; } // Otherwise, add what is possible reader.MoveToContent(); string key = string.Empty; string temptype = reader.Name; bool containsItems = false; // Create a new machine MachineType machineType = 0x0; if (reader.GetAttribute("isbios").AsYesNo() == true) { machineType |= MachineType.Bios; } if (reader.GetAttribute("isdevice").AsYesNo() == true) // Listxml-specific, used by older DATs { machineType |= MachineType.Device; } if (reader.GetAttribute("ismechanical").AsYesNo() == true) // Listxml-specific, used by older DATs { machineType |= MachineType.Mechanical; } string dirsString = (dirs != null && dirs.Count() > 0 ? string.Join("/", dirs) + "/" : string.Empty); Machine machine = new Machine { Name = dirsString + reader.GetAttribute("name"), Description = dirsString + reader.GetAttribute("name"), SourceFile = reader.GetAttribute("sourcefile"), Board = reader.GetAttribute("board"), RebuildTo = reader.GetAttribute("rebuildto"), Runnable = reader.GetAttribute("runnable").AsRunnable(), // Used by older DATs CloneOf = reader.GetAttribute("cloneof"), RomOf = reader.GetAttribute("romof"), SampleOf = reader.GetAttribute("sampleof"), MachineType = (machineType == 0x0 ? MachineType.NULL : machineType), }; if (Header.Type == "SuperDAT" && !keep) { string tempout = Regex.Match(machine.Name, @".*?\\(.*)").Groups[1].Value; if (!string.IsNullOrWhiteSpace(tempout)) { machine.Name = tempout; } } while (!reader.EOF) { // We only want elements if (reader.NodeType != XmlNodeType.Element) { reader.Read(); continue; } // Get the roms from the machine switch (reader.Name) { case "comment": // There can be multiple comments by spec machine.Comment += reader.ReadElementContentAsString(); break; case "description": machine.Description = reader.ReadElementContentAsString(); break; case "year": machine.Year = reader.ReadElementContentAsString(); break; case "manufacturer": machine.Manufacturer = reader.ReadElementContentAsString(); break; case "publisher": // Not technically supported but used by some legacy DATs machine.Publisher = reader.ReadElementContentAsString(); break; case "category": // Not technically supported but used by some legacy DATs machine.Category = reader.ReadElementContentAsString(); break; case "trurip": // This is special metadata unique to EmuArc ReadTruRip(reader.ReadSubtree(), machine); // Skip the trurip node now that we've processed it reader.Skip(); break; case "archive": containsItems = true; DatItem archive = new Archive { Name = reader.GetAttribute("name"), Source = new Source { Index = indexId, Name = filename, }, }; archive.CopyMachineInformation(machine); // Now process and add the archive key = ParseAddHelper(archive); reader.Read(); break; case "biosset": containsItems = true; DatItem biosSet = new BiosSet { Name = reader.GetAttribute("name"), Description = reader.GetAttribute("description"), Default = reader.GetAttribute("default").AsYesNo(), Source = new Source { Index = indexId, Name = filename, }, }; biosSet.CopyMachineInformation(machine); // Now process and add the biosSet key = ParseAddHelper(biosSet); reader.Read(); break; case "disk": containsItems = true; DatItem disk = new Disk { Name = reader.GetAttribute("name"), MD5 = reader.GetAttribute("md5"), SHA1 = reader.GetAttribute("sha1"), MergeTag = reader.GetAttribute("merge"), ItemStatus = reader.GetAttribute("status").AsItemStatus(), Source = new Source { Index = indexId, Name = filename, }, }; disk.CopyMachineInformation(machine); // Now process and add the disk key = ParseAddHelper(disk); reader.Read(); break; case "media": containsItems = true; DatItem media = new Media { Name = reader.GetAttribute("name"), MD5 = reader.GetAttribute("md5"), SHA1 = reader.GetAttribute("sha1"), SHA256 = reader.GetAttribute("sha256"), SpamSum = reader.GetAttribute("spamsum"), Source = new Source { Index = indexId, Name = filename, }, }; media.CopyMachineInformation(machine); // Now process and add the media key = ParseAddHelper(media); reader.Read(); break; case "release": containsItems = true; DatItem release = new Release { Name = reader.GetAttribute("name"), Region = reader.GetAttribute("region"), Language = reader.GetAttribute("language"), Date = reader.GetAttribute("date"), Default = reader.GetAttribute("default").AsYesNo(), }; release.CopyMachineInformation(machine); // Now process and add the release key = ParseAddHelper(release); reader.Read(); break; case "rom": containsItems = true; DatItem rom = new Rom { Name = reader.GetAttribute("name"), Size = Sanitizer.CleanLong(reader.GetAttribute("size")), CRC = reader.GetAttribute("crc"), MD5 = reader.GetAttribute("md5"), #if NET_FRAMEWORK RIPEMD160 = reader.GetAttribute("ripemd160"), #endif SHA1 = reader.GetAttribute("sha1"), SHA256 = reader.GetAttribute("sha256"), SHA384 = reader.GetAttribute("sha384"), SHA512 = reader.GetAttribute("sha512"), SpamSum = reader.GetAttribute("spamsum"), MergeTag = reader.GetAttribute("merge"), ItemStatus = reader.GetAttribute("status").AsItemStatus(), Date = Sanitizer.CleanDate(reader.GetAttribute("date")), Inverted = reader.GetAttribute("inverted").AsYesNo(), Source = new Source { Index = indexId, Name = filename, }, }; rom.CopyMachineInformation(machine); // Now process and add the rom key = ParseAddHelper(rom); reader.Read(); break; case "sample": containsItems = true; DatItem sample = new Sample { Name = reader.GetAttribute("name"), Source = new Source { Index = indexId, Name = filename, }, }; sample.CopyMachineInformation(machine); // Now process and add the sample key = ParseAddHelper(sample); reader.Read(); break; default: reader.Read(); break; } } // If no items were found for this machine, add a Blank placeholder if (!containsItems) { Blank blank = new Blank() { Source = new Source { Index = indexId, Name = filename, }, }; blank.CopyMachineInformation(machine); // Now process and add the rom ParseAddHelper(blank); } }
private bool ReadSheetRow(XlsxWorksheet sheet) { if (null == _xmlReader) { return(false); } if (_emptyRowCount != 0) { _cellsValues = new object[sheet.ColumnsCount]; _emptyRowCount--; _depth++; return(true); } if (_savedCellsValues != null) { _cellsValues = _savedCellsValues; _savedCellsValues = null; _depth++; return(true); } if ((_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_row) || _xmlReader.ReadToFollowing(XlsxWorksheet.N_row, _namespaceUri)) { _cellsValues = new object[sheet.ColumnsCount]; int rowIndex = int.Parse(_xmlReader.GetAttribute(XlsxWorksheet.A_r)); if (rowIndex != (_depth + 1)) { if (rowIndex != (_depth + 1)) { _emptyRowCount = rowIndex - _depth - 1; } } bool hasValue = false; string a_s = String.Empty; string a_t = String.Empty; string a_r = String.Empty; int col = 0; int row = 0; while (_xmlReader.Read()) { if (_xmlReader.Depth == 2) { break; } if (_xmlReader.NodeType == XmlNodeType.Element) { hasValue = false; if (_xmlReader.LocalName == XlsxWorksheet.N_c) { a_s = _xmlReader.GetAttribute(XlsxWorksheet.A_s); a_t = _xmlReader.GetAttribute(XlsxWorksheet.A_t); a_r = _xmlReader.GetAttribute(XlsxWorksheet.A_r); XlsxDimension.XlsxDim(a_r, out col, out row); } else if (_xmlReader.LocalName == XlsxWorksheet.N_v || _xmlReader.LocalName == XlsxWorksheet.N_t) { hasValue = true; } } if (_xmlReader.NodeType == XmlNodeType.Text && hasValue) { double number; object o = _xmlReader.Value; var style = NumberStyles.Any; var culture = CultureInfo.InvariantCulture; if (double.TryParse(o.ToString(), style, culture, out number)) { o = number; } if (null != a_t && a_t == XlsxWorksheet.A_s) //if string { o = Helpers.ConvertEscapeChars(_workbook.SST[int.Parse(o.ToString())]); } // Requested change 4: missing (it appears that if should be else if) else if (null != a_t && a_t == XlsxWorksheet.N_inlineStr) //if string inline { o = Helpers.ConvertEscapeChars(o.ToString()); } else if (a_t == "b") //boolean { o = _xmlReader.Value == "1"; } else if (null != a_s) //if something else { XlsxXf xf = _workbook.Styles.CellXfs[int.Parse(a_s)]; if (xf.ApplyNumberFormat && o != null && o.ToString() != string.Empty && IsDateTimeStyle(xf.NumFmtId)) { o = Helpers.ConvertFromOATime(number); } else if (xf.NumFmtId == 49) { o = o.ToString(); } } if (col - 1 < _cellsValues.Length) { _cellsValues[col - 1] = o; } } } if (_emptyRowCount > 0) { _savedCellsValues = _cellsValues; return(ReadSheetRow(sheet)); } _depth++; return(true); } _xmlReader.Close(); if (_sheetStream != null) { _sheetStream.Close(); } return(false); }
public virtual void ReadXml(XmlReader reader) { IsSilent = bool.Parse(reader.GetAttribute("silent")); }
/// <summary> /// Parses the response XML for a container listing operation. /// </summary> /// <returns>An enumerable collection of <see cref="BlobContainerEntry"/> objects.</returns> internal static async Task <ListContainersResponse> ParseAsync(Stream stream, CancellationToken token) { using (XmlReader reader = XMLReaderExtensions.CreateAsAsync(stream)) { token.ThrowIfCancellationRequested(); List <BlobContainerEntry> entries = new List <BlobContainerEntry>(); string nextMarker = default(string); if (await reader.ReadToFollowingAsync(Constants.EnumerationResultsElement).ConfigureAwait(false)) { if (reader.IsEmptyElement) { await reader.SkipAsync().ConfigureAwait(false); } else { Uri baseUri = new Uri(reader.GetAttribute(Constants.ServiceEndpointElement)); await reader.ReadStartElementAsync().ConfigureAwait(false); while (await reader.IsStartElementAsync().ConfigureAwait(false)) { token.ThrowIfCancellationRequested(); if (reader.IsEmptyElement) { await reader.SkipAsync().ConfigureAwait(false); } else { switch (reader.Name) { case Constants.MarkerElement: await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.NextMarkerElement: nextMarker = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.MaxResultsElement: await reader.ReadElementContentAsInt32Async().ConfigureAwait(false); break; case Constants.PrefixElement: await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); break; case Constants.ContainersElement: await reader.ReadStartElementAsync().ConfigureAwait(false); while (await reader.IsStartElementAsync(Constants.ContainerElement).ConfigureAwait(false)) { entries.Add(await ParseContainerEntryAsync(reader, baseUri, token).ConfigureAwait(false)); } await reader.ReadEndElementAsync().ConfigureAwait(false); break; default: await reader.SkipAsync().ConfigureAwait(false); break; } } } await reader.ReadEndElementAsync().ConfigureAwait(false); } } return(new ListContainersResponse { Containers = entries, NextMarker = nextMarker }); } }
private void ReadSheetGlobals(XlsxWorksheet sheet) { if (_xmlReader != null) { _xmlReader.Close(); } if (_sheetStream != null) { _sheetStream.Close(); } _sheetStream = _zipWorker.GetWorksheetStream(sheet.Path); if (null == _sheetStream) { return; } _xmlReader = XmlReader.Create(_sheetStream); //count rows and cols in case there is no dimension elements int rows = 0; int cols = 0; _namespaceUri = null; int biggestColumn = 0; //used when no col elements and no dimension while (_xmlReader.Read()) { if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_worksheet) { //grab the namespaceuri from the worksheet element _namespaceUri = _xmlReader.NamespaceURI; } if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_dimension) { string dimValue = _xmlReader.GetAttribute(XlsxWorksheet.A_ref); sheet.Dimension = new XlsxDimension(dimValue); break; } //removed: Do not use col to work out number of columns as this is really for defining formatting, so may not contain all columns //if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_col) // cols++; if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_row) { rows++; } //check cells so we can find size of sheet if can't work it out from dimension or col elements (dimension should have been set before the cells if it was available) //ditto for cols if (sheet.Dimension == null && cols == 0 && _xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_c) { var refAttribute = _xmlReader.GetAttribute(XlsxWorksheet.A_r); if (refAttribute != null) { var thisRef = ReferenceHelper.ReferenceToColumnAndRow(refAttribute); if (thisRef[1] > biggestColumn) { biggestColumn = thisRef[1]; } } } } //if we didn't get a dimension element then use the calculated rows/cols to create it if (sheet.Dimension == null) { if (cols == 0) { cols = biggestColumn; } if (rows == 0 || cols == 0) { sheet.IsEmpty = true; return; } sheet.Dimension = new XlsxDimension(rows, cols); //we need to reset our position to sheet data _xmlReader.Close(); _sheetStream.Close(); _sheetStream = _zipWorker.GetWorksheetStream(sheet.Path); _xmlReader = XmlReader.Create(_sheetStream); } //read up to the sheetData element. if this element is empty then there aren't any rows and we need to null out dimension _xmlReader.ReadToFollowing(XlsxWorksheet.N_sheetData, _namespaceUri); if (_xmlReader.IsEmptyElement) { sheet.IsEmpty = true; } }
/// <summary> /// Fills a function signature object from an XML fragment. /// </summary> /// <param name="reader">The XML reader containing the fragment to read.</param> /// <exception cref="ArgumentNullException">If <paramref name="reader" /> is <c>null</c>.</exception> /// <exception cref="LSLLibraryDataXmlSyntaxException"> /// On missing or unknown attributes. /// If a parameter 'Name' is used more than once. /// If a parameter 'Name' is whitespace. /// If a parameter 'Type' is <see cref="LSLType.Void" /> and not Variadic. /// If a parameter 'Type' does not correspond to an <see cref="LSLType" /> enumeration member. /// If a 'Properties' node 'Name' is <c>null</c> or whitespace. /// If a 'Properties' node 'Name' is used more than once. /// If a 'Properties' node 'Value' is <c>null</c> or whitespace. /// </exception> /// <exception cref="LSLInvalidSymbolNameException"> /// Thrown if the function signatures name or any of its parameters names /// do not abide by LSL symbol naming conventions. /// </exception> /// <exception cref="XmlException">Incorrect XML encountered in the input stream. </exception> /// <exception cref="LSLInvalidSubsetNameException"> /// Thrown if any of the given subset names in the 'Subsets' CSV string do /// not match the pattern ([a-zA-Z]+[a-zA-Z_0-9\\-]*). /// </exception> void IXmlSerializable.ReadXml(XmlReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } var parameterNames = new HashSet <string>(); var lineNumberInfo = (IXmlLineInfo)reader; reader.MoveToContent(); var hasReturnType = false; var hasSubsets = false; var hasName = false; while (reader.MoveToNextAttribute()) { if (reader.Name == "Subsets") { Subsets.SetSubsets(reader.Value); hasSubsets = true; } else if (reader.Name == "ReturnType") { LSLType type; if (Enum.TryParse(reader.Value, out type)) { ReturnType = type; hasReturnType = true; } else { throw new LSLLibraryDataXmlSyntaxException(lineNumberInfo.LineNumber, string.Format("LibraryFunction{0}: ReturnType attribute Value '{1}' invalid.", hasName ? (" '" + Name + "'") : "", reader.Value)); } } else if (reader.Name == "Name") { hasName = true; Name = reader.Value; } else { throw new LSLLibraryDataXmlSyntaxException(lineNumberInfo.LineNumber, string.Format("LibraryFunction{0}: Unknown attribute '{1}'.", hasName ? (" '" + Name + "'") : "", reader.Name)); } } if (!hasName) { throw new LSLLibraryDataXmlSyntaxException(lineNumberInfo.LineNumber, "LibraryFunction: Missing Name attribute."); } if (!hasReturnType) { throw new LSLLibraryDataXmlSyntaxException(lineNumberInfo.LineNumber, string.Format("LibraryFunction '{0}': Missing ReturnType attribute.", Name)); } if (!hasSubsets) { throw new LSLLibraryDataXmlSyntaxException(lineNumberInfo.LineNumber, string.Format("LibraryFunction '{0}': Missing Subsets attribute.", Name)); } var isVariadic = false; var canRead = reader.Read(); while (canRead) { if ((reader.Name == "Parameter") && reader.IsStartElement()) { if (isVariadic) { throw new LSLLibraryDataXmlSyntaxException(lineNumberInfo.LineNumber, string.Format("LibraryFunction '{0}': More than one variadic parameter was defined.", Name)); } var pName = reader.GetAttribute("Name"); if (string.IsNullOrWhiteSpace(pName)) { throw new LSLLibraryDataXmlSyntaxException(lineNumberInfo.LineNumber, string.Format( "LibraryFunction '{0}': Parameter Name attribute invalid, cannot be empty or whitespace.", Name)); } LSLType pType; if (!Enum.TryParse(reader.GetAttribute("Type"), out pType)) { throw new LSLLibraryDataXmlSyntaxException(lineNumberInfo.LineNumber, string.Format( "LibraryFunction '{0}': Parameter named '{1}' has an invalid Type attribute.", Name, pName)); } if (parameterNames.Contains(pName)) { throw new LSLLibraryDataXmlSyntaxException(lineNumberInfo.LineNumber, string.Format("LibraryFunction '{0}': Parameter Name '{1}' already used.", Name, pName)); } var variadic = reader.GetAttribute("Variadic"); if (!string.IsNullOrWhiteSpace(variadic)) { if (variadic.ToLower() == "true") { isVariadic = true; } else if (variadic.ToLower() != "false") { throw new LSLLibraryDataXmlSyntaxException(lineNumberInfo.LineNumber, string.Format( "LibraryFunction '{0}': Variadic attribute in parameter #{1} of Function '{2}' must equal True or False (Case Insensitive).", Name, pName, Name)); } } if (pType == LSLType.Void && !isVariadic) { throw new LSLLibraryDataXmlSyntaxException(lineNumberInfo.LineNumber, string.Format( "LibraryFunction '{0}': Parameter Type invalid, function parameters cannot be Void unless they are declared variadic.", Name)); } parameterNames.Add(pName); AddParameter(new LSLParameterSignature(pType, pName, isVariadic)); canRead = reader.Read(); } else if ((reader.Name == "DocumentationString") && reader.IsStartElement()) { DocumentationString = reader.ReadElementContentAsString(); canRead = reader.Read(); } else if ((reader.Name == "Property") && reader.IsStartElement()) { var pName = reader.GetAttribute("Name"); if (string.IsNullOrWhiteSpace(pName)) { throw new LSLLibraryDataXmlSyntaxException(lineNumberInfo.LineNumber, string.Format("LibraryFunction '{0}': Property element's Name attribute cannot be empty.", Name)); } var value = reader.GetAttribute("Value"); if (string.IsNullOrWhiteSpace(value)) { throw new LSLLibraryDataXmlSyntaxException(lineNumberInfo.LineNumber, string.Format("LibraryFunction '{0}': Property element's Value attribute cannot be empty.", Name)); } if (_properties.ContainsKey(pName)) { throw new LSLLibraryDataXmlSyntaxException(lineNumberInfo.LineNumber, string.Format("LibraryFunction '{0}': Property name '{1}' has already been used.", Name, pName)); } _properties.Add(pName, value); canRead = reader.Read(); } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "LibraryFunction") { break; } else { canRead = reader.Read(); } } }
//DOC: Documentation Required /// <summary> /// /// </summary> public override string GetAttribute(int i) { string attributeValue = innerReader.GetAttribute(i); return(attributeValue); }
public object ReadObject(Type type) { if (serialized_object_count++ == serializer.MaxItemsInObjectGraph) { throw SerializationError(String.Format("The object graph exceeded the maximum object count '{0}' specified in the serializer", serializer.MaxItemsInObjectGraph)); } bool nullable = false; if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>)) { nullable = true; type = Nullable.GetUnderlyingType(type); } bool isNull = reader.GetAttribute("type") == "null"; switch (Type.GetTypeCode(type)) { case TypeCode.DBNull: string dbn = reader.ReadElementContentAsString(); if (dbn != String.Empty) { throw new SerializationException(String.Format("The only expected DBNull value string is '{{}}'. Tha actual input was '{0}'.", dbn)); } return(DBNull.Value); case TypeCode.String: if (isNull) { reader.ReadElementContentAsString(); return(null); } else { return(reader.ReadElementContentAsString()); } case TypeCode.Char: var c = reader.ReadElementContentAsString(); if (c.Length > 1) { throw new XmlException("Invalid JSON char"); } return(Char.Parse(c)); case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return(ReadValueType(type, nullable)); case TypeCode.Byte: case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.Int64: if (type.IsEnum) { return(Enum.ToObject(type, Convert.ChangeType(reader.ReadElementContentAsLong(), Enum.GetUnderlyingType(type), null))); } else { return(ReadValueType(type, nullable)); } case TypeCode.UInt64: if (type.IsEnum) { return(Enum.ToObject(type, Convert.ChangeType(reader.ReadElementContentAsDecimal(), Enum.GetUnderlyingType(type), null))); } else { return(ReadValueType(type, nullable)); } case TypeCode.Boolean: return(ReadValueType(type, nullable)); case TypeCode.DateTime: // it does not use ReadElementContentAsDateTime(). Different string format. var s = reader.ReadElementContentAsString(); if (s.Length < 2 || !s.StartsWith("/Date(", StringComparison.Ordinal) || !s.EndsWith(")/", StringComparison.Ordinal)) { if (nullable) { return(null); } throw new XmlException("Invalid JSON DateTime format. The value format should be '/Date(UnixTime)/'"); } // The date can contain [SIGN]LONG, [SIGN]LONG+HOURSMINUTES or [SIGN]LONG-HOURSMINUTES // the format for HOURSMINUTES is DDDD int tidx = s.IndexOf('-', 8); if (tidx == -1) { tidx = s.IndexOf('+', 8); } int minutes = 0; if (tidx == -1) { s = s.Substring(6, s.Length - 8); } else { int offset; int.TryParse(s.Substring(tidx + 1, s.Length - 3 - tidx), out offset); minutes = (offset % 100) + (offset / 100) * 60; if (s [tidx] == '-') { minutes = -minutes; } s = s.Substring(6, tidx - 6); } var date = new DateTime(1970, 1, 1).AddMilliseconds(long.Parse(s)); if (minutes != 0) { date = date.AddMinutes(minutes); } return(date); default: if (type == typeof(Guid)) { return(new Guid(reader.ReadElementContentAsString())); } else if (type == typeof(Uri)) { if (isNull) { reader.ReadElementContentAsString(); return(null); } else { return(new Uri(reader.ReadElementContentAsString(), UriKind.RelativeOrAbsolute)); } } else if (type == typeof(XmlQualifiedName)) { s = reader.ReadElementContentAsString(); int idx = s.IndexOf(':'); return(idx < 0 ? new XmlQualifiedName(s) : new XmlQualifiedName(s.Substring(0, idx), s.Substring(idx + 1))); } else if (type != typeof(object)) { // strongly-typed object if (reader.IsEmptyElement) { // empty -> null array or object reader.Read(); return(null); } Type ct = GetCollectionElementType(type); if (ct != null) { return(DeserializeGenericCollection(type, ct)); } else { TypeMap map = GetTypeMap(type); return(map.Deserialize(this)); } } else { return(ReadInstanceDrivenObject()); } } }
public override void gaxb_load(XmlReader reader, object _parent, Hashtable args) { base.gaxb_load(reader, _parent, args); if(reader == null && _parent == null) return; parent = _parent; if(this.GetType() == typeof( PUMovie )) { gaxb_addToParent(); } xmlns = reader.GetAttribute("xmlns"); string attr; attr = reader.GetAttribute("hasAlpha"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr != null) { hasAlpha = bool.Parse(attr); hasAlphaExists = true; } attr = reader.GetAttribute("looping"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr != null) { looping = bool.Parse(attr); loopingExists = true; } attr = reader.GetAttribute("resourcePath"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr != null) { resourcePath = attr; resourcePathExists = true; } attr = reader.GetAttribute("shader"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr != null) { shader = attr; shaderExists = true; } attr = reader.GetAttribute("anchor"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr == null) { attr = "0,0"; } if(attr != null) { anchor = attr; anchorExists = true; } attr = reader.GetAttribute("color"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr != null) { color = attr; colorExists = true; } }
public void Log4JXmlTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout='${log4jxmlevent:includeCallSite=true:includeSourceInfo=true:includeMdc=true:includeMdlc=true:includeMdlc=true:IncludeAllProperties=true:ndcItemSeparator=\:\::includenlogdata=true}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); MappedDiagnosticsContext.Clear(); NestedDiagnosticsContext.Clear(); MappedDiagnosticsContext.Set("foo1", "bar1"); MappedDiagnosticsContext.Set("foo2", "bar2"); MappedDiagnosticsLogicalContext.Clear(); MappedDiagnosticsLogicalContext.Set("foo3", "bar3"); NestedDiagnosticsContext.Push("baz1"); NestedDiagnosticsContext.Push("baz2"); NestedDiagnosticsContext.Push("baz3"); ILogger logger = LogManager.GetLogger("A"); var logEventInfo = LogEventInfo.Create(LogLevel.Debug, "A", new Exception("Hello Exception", new Exception("Goodbye Exception")), null, "some message"); logEventInfo.Properties["nlogPropertyKey"] = "nlogPropertyValue"; logger.Log(logEventInfo); string result = GetDebugLastMessage("debug"); string wrappedResult = "<log4j:dummyRoot xmlns:log4j='http://log4j' xmlns:nlog='http://nlog'>" + result + "</log4j:dummyRoot>"; Assert.NotEqual("", result); // make sure the XML can be read back and verify some fields StringReader stringReader = new StringReader(wrappedResult); using (XmlReader reader = XmlReader.Create(stringReader)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Prefix == "log4j") { switch (reader.LocalName) { case "dummyRoot": break; case "event": Assert.Equal("DEBUG", reader.GetAttribute("level")); Assert.Equal("A", reader.GetAttribute("logger")); var epochStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); long timestamp = Convert.ToInt64(reader.GetAttribute("timestamp")); var time = epochStart.AddMilliseconds(timestamp); var now = DateTime.UtcNow; Assert.True(now.Ticks - time.Ticks < TimeSpan.FromSeconds(3).Ticks); Assert.Equal(Thread.CurrentThread.ManagedThreadId.ToString(), reader.GetAttribute("thread")); break; case "message": reader.Read(); Assert.Equal("some message", reader.Value); break; case "NDC": reader.Read(); Assert.Equal("baz3::baz2::baz1", reader.Value); break; case "locationInfo": Assert.Equal(MethodBase.GetCurrentMethod().DeclaringType.FullName, reader.GetAttribute("class")); Assert.Equal(MethodBase.GetCurrentMethod().ToString(), reader.GetAttribute("method")); break; case "properties": break; case "throwable": reader.Read(); Assert.True(reader.Value.Contains("Hello Exception")); Assert.True(reader.Value.Contains("Goodbye Exception")); break; case "data": string name = reader.GetAttribute("name"); string value = reader.GetAttribute("value"); switch (name) { case "log4japp": Assert.Equal(AppDomain.CurrentDomain.FriendlyName + "(" + Process.GetCurrentProcess().Id + ")", value); break; case "log4jmachinename": Assert.Equal(Environment.MachineName, value); break; case "foo1": Assert.Equal("bar1", value); break; case "foo2": Assert.Equal("bar2", value); break; case "foo3": Assert.Equal("bar3", value); break; case "nlogPropertyKey": Assert.Equal("nlogPropertyValue", value); break; default: Assert.True(false, "Unknown <log4j:data>: " + name); break; } break; default: throw new NotSupportedException("Unknown element: " + reader.LocalName); } continue; } if (reader.NodeType == XmlNodeType.Element && reader.Prefix == "nlog") { switch (reader.LocalName) { case "eventSequenceNumber": break; case "locationInfo": Assert.Equal(this.GetType().Assembly.FullName, reader.GetAttribute("assembly")); break; case "properties": break; case "data": var name = reader.GetAttribute("name"); var value = reader.GetAttribute("value"); Assert.Equal("nlogPropertyKey", name); Assert.Equal("nlogPropertyValue", value); break; default: throw new NotSupportedException("Unknown element: " + reader.LocalName); } } } } }
public override void gaxb_load(XmlReader reader, object _parent, Hashtable args) { base.gaxb_load(reader, _parent, args); if(reader == null && _parent == null) return; parent = _parent; if(this.GetType() == typeof( PUSimpleTable )) { gaxb_addToParent(); } //xmlns = reader.GetAttribute("xmlns"); string attr; attr = reader.GetAttribute("cellSize"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { cellSize = new Vector2().PUParse(attr); } attr = reader.GetAttribute("headerSize"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr == null) { attr = "0,0"; } if(attr != null) { headerSize = new Vector2().PUParse(attr); } attr = reader.GetAttribute("asynchronous"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr == null) { attr = "true"; } if(attr != null) { asynchronous = bool.Parse(attr); } }
public static void HeslarXml(string strVstupniSoubor, string strVystupniSoubor, Dictionary <string, ZpracovatTagProHeslarXml> gztTagyZpracovani) { char[] chIndexy = schIndexy; char[] chSeparatory = schSeparatory; using (XmlReader r = Objekty.VytvorXmlReader(strVstupniSoubor)) { using (XmlWriter xwHeslar = Objekty.VytvorXmlWriter(strVystupniSoubor)) { xwHeslar.WriteStartDocument(true); xwHeslar.WriteStartElement("heslar"); string strNazevTagu = null; HesloInfo hiHeslo = null; PismenoInfo piPismeno = null; HeslovaStatInfo hsiHeslovaStat = null; #region WHILE while (r.Read()) { strNazevTagu = r.Name; if (r.NodeType == XmlNodeType.Element) { if (gztTagyZpracovani != null && gztTagyZpracovani.ContainsKey(strNazevTagu)) { gztTagyZpracovani[strNazevTagu](r, xwHeslar, piPismeno, hsiHeslovaStat, hiHeslo); } else { #region SWITCH switch (r.Name) { case "dictionary": string sSource = r.GetAttribute("name"); xwHeslar.WriteAttributeString("dictionary", sSource); break; case "div1": piPismeno = new PismenoInfo(); piPismeno.Id = r.GetAttribute("id"); piPismeno.Text = r.GetAttribute("text"); VypisZacatekPismene(xwHeslar, piPismeno); break; /* * case "entryref": * iHw = 0; * xwHeslar.WriteStartElement("heslovaStat"); * sIdEntry = r.GetAttribute("id"); * xwHeslar.WriteAttributeString("id", sIdEntry); * xwHeslar.WriteAttributeString("type", "ref"); * break; */ case "entry": //iHw = 0; hsiHeslovaStat = new HeslovaStatInfo(); hsiHeslovaStat.Id = r.GetAttribute("id"); hsiHeslovaStat.Typ = r.GetAttribute("type"); xwHeslar.WriteStartElement("heslovaStat"); Transformace.SerializeAttributes(r, xwHeslar, false); //sIdEntry = r.GetAttribute("id"); //xwHeslar.WriteAttributeString("id", sIdEntry); //string sTypEntry = r.GetAttribute("type"); //if (null != sTypEntry) // xwHeslar.WriteAttributeString("type", sTypEntry); break; case "hw": //zkontrolovat, jestli odstavec obsahuje "nenáležitá podoba" - a pak heslo vyřadit/označit jako interní //jenže akce následuje až za heslovým slovem string sForma = r.GetAttribute("form"); Transformace.SerializeNode(r, xwHeslar); string strHeslo = r.ReadString(); strHeslo = strHeslo.Trim(); for (int i = 0; i < chIndexy.Length; i++) { if (strHeslo.Contains(chIndexy[i].ToString())) { strHeslo = strHeslo.Remove(strHeslo.IndexOf(chIndexy[i]), 1); //xwHeslar.WriteAttributeString("hom", chIndexy[i].ToString()); break; } } if (strHeslo.IndexOf('-') == strHeslo.Length - 1 || strHeslo.IndexOf('-') == 0) { if (sForma == null) { xwHeslar.WriteAttributeString("form", "short"); } } if (strHeslo.Contains("(?)")) { strHeslo = strHeslo.Replace("(?)", ""); //otazník v závorce za heslem } strHeslo = strHeslo.TrimEnd(chSeparatory); strHeslo = strHeslo.TrimEnd(); //strHeslo = strHeslo.TrimEnd(chIndexy); if (strHeslo.Length > 0) { char chPismeno = strHeslo[0]; if (chPismeno == '*' || chPismeno == '\u02E3') // || chPismeno == '\u02DF') - zobrazovalo se špatně v IE //nemělo by se takové heslo upravit tak, že se odstraní první znak? { xwHeslar.WriteAttributeString("pref", strHeslo.Substring(0, 1)); } xwHeslar.WriteString(strHeslo); } break; } #endregion } } #region IF2 if (r.NodeType == XmlNodeType.EndElement) { if (gztTagyZpracovani != null && gztTagyZpracovani.ContainsKey(strNazevTagu)) { gztTagyZpracovani[strNazevTagu](r, xwHeslar, piPismeno, hsiHeslovaStat, hiHeslo); } else { switch (r.Name) { case "div1": xwHeslar.WriteEndElement(); break; case "entry": xwHeslar.WriteEndElement(); break; case "hw": xwHeslar.WriteEndElement(); break; } } } #endregion } #endregion } } }
public override void gaxb_load(XmlReader reader, object _parent, Hashtable args) { base.gaxb_load(reader, _parent, args); if(reader == null && _parent == null) return; parent = _parent; if(this.GetType() == typeof( PUHorizontalLayoutGroup )) { gaxb_addToParent(); } xmlns = reader.GetAttribute("xmlns"); string attr; attr = reader.GetAttribute("spacing"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr == null) { attr = "0"; } if(attr != null) { spacing = float.Parse(attr); } attr = reader.GetAttribute("padding"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr == null) { attr = "0,0,0,0"; } if(attr != null) { padding = new Vector4().PUParse(attr); } attr = reader.GetAttribute("childAlignment"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { childAlignment = (PlanetUnity2.GridLayoutChildAlignment)Enum.Parse(typeof(PlanetUnity2.GridLayoutChildAlignment), attr); } }
public static void HeslarXml(string strVstupniSoubor, string strVystupniSoubor) { char[] chIndexy = schIndexy; char[] chSeparatory = schSeparatory; using (XmlReader r = Objekty.VytvorXmlReader(strVstupniSoubor)) { using (XmlWriter xwHeslar = Objekty.VytvorXmlWriter(strVystupniSoubor)) { xwHeslar.WriteStartDocument(true); xwHeslar.WriteStartElement("heslar"); #region WHILE while (r.Read()) { if (r.NodeType == XmlNodeType.Element) { #region SWITCH switch (r.Name) { case "dictionary": string sSource = r.GetAttribute("name"); xwHeslar.WriteAttributeString("dictionary", sSource); break; case "div1": xwHeslar.WriteStartElement("pismeno"); xwHeslar.WriteAttributeString("id", r.GetAttribute("id")); xwHeslar.WriteAttributeString("text", r.GetAttribute("text")); break; /* * case "entryref": * iHw = 0; * xwHeslar.WriteStartElement("heslovaStat"); * sIdEntry = r.GetAttribute("id"); * xwHeslar.WriteAttributeString("id", sIdEntry); * xwHeslar.WriteAttributeString("type", "ref"); * break; */ case "entry": //iHw = 0; xwHeslar.WriteStartElement("heslovaStat"); Transformace.SerializeAttributes(r, xwHeslar, false); //sIdEntry = r.GetAttribute("id"); //xwHeslar.WriteAttributeString("id", sIdEntry); //string sTypEntry = r.GetAttribute("type"); //if (null != sTypEntry) // xwHeslar.WriteAttributeString("type", sTypEntry); break; case "hwo": case "hw": //zkontrolovat, jestli odstavec obsahuje "nenáležitá podoba" - a pak heslo vyřadit/označit jako interní //jenže akce následuje až za heslovým slovem string sForma = r.GetAttribute("form"); string sHom = r.GetAttribute("hom"); Transformace.SerializeNode(r, xwHeslar); string strHeslo = r.ReadString(); strHeslo = strHeslo.Trim(); for (int i = 0; i < chIndexy.Length; i++) { if (strHeslo.Contains(chIndexy[i].ToString())) { strHeslo = strHeslo.Remove(strHeslo.IndexOf(chIndexy[i]), 1); if (sHom == null) { xwHeslar.WriteAttributeString("hom", chIndexy[i].ToString()); //je potřeba to zapisovat, nebo ne? } break; } } if (strHeslo.IndexOf('-') == strHeslo.Length - 1 || strHeslo.IndexOf('-') == 0) { if (sForma == null) { xwHeslar.WriteAttributeString("form", "short"); } } if (strHeslo.Contains("(?)")) { strHeslo = strHeslo.Replace("(?)", ""); //otazník v závorce za heslem } strHeslo = strHeslo.TrimEnd(chSeparatory); strHeslo = strHeslo.TrimEnd(); //strHeslo = strHeslo.TrimEnd(chIndexy); if (strHeslo.Length > 0) { char chPismeno = strHeslo[0]; if (chPismeno == '*' || chPismeno == '\u02E3') // || chPismeno == '\u02DF') - zobrazovalo se špatně v IE //nemělo by se takové heslo upravit tak, že se odstraní první znak? { xwHeslar.WriteAttributeString("pref", strHeslo.Substring(0, 1)); } xwHeslar.WriteString(strHeslo); } /* * while (r.Name != "") * { * r.Read(); * } * SerializeNode(r, xwHeslar); */ /* * string sTyp = r.GetAttribute("type"); * string strHeslo = r.ReadString(); * strHeslo = strHeslo.Trim(); * strHeslo = strHeslo.TrimEnd(chSeparatory); * strHeslo = strHeslo.TrimEnd(); * string[] aHesla = strHeslo.Split(chSeparatory); * foreach (string s in aHesla) { * string sText = s.Trim(); * if (s.Length > 0) { * xwHeslar.WriteStartElement("hw"); * if (sTyp != null) * xwHeslar.WriteAttributeString("type",sTyp); ++iHw; * xwHeslar.WriteAttributeString("id", sIdEntry + ".hw" + iHw.ToString()); * * xwHeslar.WriteString(sText); * xwHeslar.WriteEndElement(); * } * } */ break; } #endregion } #region IF2 if (r.NodeType == XmlNodeType.EndElement) { switch (r.Name) { case "div1": xwHeslar.WriteEndElement(); break; case "entry": xwHeslar.WriteEndElement(); break; case "hwo": case "hw": xwHeslar.WriteEndElement(); break; } } #endregion } #endregion } } }
public override void gaxb_load(XmlReader reader, object _parent, Hashtable args) { base.gaxb_load(reader, _parent, args); if(reader == null && _parent == null) return; parent = _parent; if(this.GetType() == typeof( PUSlider )) { gaxb_addToParent(); } xmlns = reader.GetAttribute("xmlns"); string attr; attr = reader.GetAttribute("handleResourcePath"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { handleResourcePath = attr; } attr = reader.GetAttribute("handleSize"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr == null) { attr = "32,32"; } if(attr != null) { handleSize = new Vector2().PUParse(attr); } attr = reader.GetAttribute("fillResourcePath"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { fillResourcePath = attr; } attr = reader.GetAttribute("onValueChanged"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { onValueChanged = attr; } attr = reader.GetAttribute("minValue"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr == null) { attr = "0"; } if(attr != null) { minValue = float.Parse(attr); } attr = reader.GetAttribute("maxValue"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr == null) { attr = "1"; } if(attr != null) { maxValue = float.Parse(attr); } attr = reader.GetAttribute("direction"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { direction = (PlanetUnity2.SliderDirection)Enum.Parse(typeof(PlanetUnity2.SliderDirection), attr); } }
public static void HeslarText(string strVstupniSoubor, string sVystupniSoubor) { string sSubVoce = null; string sSubVoceId = null; //string sHeslo = null; //string sId = null; //string sType = null; string sHeslovaStatTyp = null; string sHeslovaStatID = null; //string sHomonymum = null; //string sRetrograd = null; string sPismeno = null; string sZdroj = null; string sPouziti = null; using (XmlReader r = Objekty.VytvorXmlReader(strVstupniSoubor)) { using (StreamWriter sw = new StreamWriter(sVystupniSoubor, false, System.Text.Encoding.Unicode)) { while (r.Read()) { if (r.NodeType == XmlNodeType.Element) { switch (r.Name) { case "hw": string[] asVlastnosti = new string[20]; HesloInfo hi = new HesloInfo(); string sRef = r.GetAttribute("ref"); string sZdrojHW = r.GetAttribute("source"); string sZdrojID = r.GetAttribute("target"); string sPrefix = r.GetAttribute("pref"); //if(r.GetAttribute("id") == "en000040.hw3") // sPrefix = r.GetAttribute("pref"); string strTyp = r.GetAttribute("type"); //asVlastnosti[0] = ""; //prefix //asVlastnosti[1] = ""; //hesloveSlovo //asVlastnosti[2] = ""; //postfix /* * asVlastnosti[3] = r.GetAttribute("hom"); * asVlastnosti[4] = ""; //slovní druh * asVlastnosti[5] = ""; //další informace * asVlastnosti[6] = ""; //varianta * * asVlastnosti[7] = r.GetAttribute("id"); * asVlastnosti[8] = r.GetAttribute("form"); * asVlastnosti[9] = strTyp; //substandard * asVlastnosti[10] = r.GetAttribute("xml:lang"); * asVlastnosti[11] = sHeslovaStatID; * asVlastnosti[12] = ""; //heslová stať * asVlastnosti[13] = sHeslovaStatTyp; * asVlastnosti[14] = sPismeno; * asVlastnosti[15] = sZdroj; */ hi.Homonymum = r.GetAttribute("hom"); hi.SlovniDruh = ""; hi.DalsiInformace = ""; hi.Varianta = ""; hi.Id = r.GetAttribute("id"); hi.Forma = r.GetAttribute("form"); hi.TypHeslovehoSlova = strTyp; //substandard hi.Lang = r.GetAttribute("xml:lang"); hi.HeslovaStatId = sHeslovaStatID; hi.HeslovaStat = ""; //heslová stať hi.HeslovaStatTyp = sHeslovaStatTyp; hi.Pismeno = sPismeno; hi.ZkratkaZdroje = sZdroj; hi.JeRef = sRef; if (strTyp == "substandard" && sZdroj == "ESSC") // hi.TypHeslovehoSlova == "1" { break; } /* * if (asVlastnosti[9] == "substandard" && sZdroj == "ESSC") { * break; * } */ if (sZdrojHW == "HesStcS") { hi.HesStcSIdRef = sZdrojID; } /* * if (sZdrojHW == "HesStcS") { * asVlastnosti[19] = sZdrojID; * } */ //if (asVlastnosti[3] == null) // asVlastnosti[3] = ""; hi.ZpusobVyuziti = sPouziti; //if (sPouziti == "internal") // hi.FormId = 1; /* * if (sPouziti == "internal") * asVlastnosti[18] = "1"; */ //logika součást get /* * switch (asVlastnosti[8]) { * case "short": * asVlastnosti[8] = "4"; * break; * case "restored": * asVlastnosti[8] = "2"; * break; * default: * asVlastnosti[8] = "1"; * break; * } * * if (asVlastnosti[9] == null) * asVlastnosti[9] = "0"; * else * asVlastnosti[9] = "1"; * * if (asVlastnosti[10] == null) { * asVlastnosti[10] = "1"; * } * * switch (sHeslovaStatTyp) { * case "ref": * asVlastnosti[13] = "4"; * break; * case "full": * asVlastnosti[13] = "2"; * break; * case "excl": //v ESSČ * asVlastnosti[13] = "8"; * break; * default: * asVlastnosti[13] = "1"; * break; * } * if (sRef == "true") { * asVlastnosti[13] = "4"; * } * * * switch (sZdroj) { * case "MSS": * asVlastnosti[15] = "2"; * break; * case "ESSC": * asVlastnosti[15] = "4"; * break; * case "GbSlov": * asVlastnosti[15] = "8"; * break; * case "StcS": * case "StcSSlov": * asVlastnosti[15] = "16"; * break; * case "SimekSlov": * asVlastnosti[15] = "32"; * break; * case "HesStcS": * case "StcSMat": * asVlastnosti[15] = "1"; * break; * default: * break; * } */ string sObsahElementu = r.ReadElementString(); if (!hi.ZpracujHesloveSlovo(sObsahElementu, sPrefix)) { break; } /* * if (hi.HesloveSlovo == "žižň") * { * string d = hi.HesloveSlovo; * } */ /* * asVlastnosti[1] = sObsahElementu; * if (!String.IsNullOrEmpty(sPrefix)) { * asVlastnosti[0] = sPrefix; * asVlastnosti[1] = asVlastnosti[1].Substring(sPrefix.Length); * } * * * if (asVlastnosti[1].Contains("(?)")) { * asVlastnosti[1] = asVlastnosti[1].Replace("(?)", "").TrimEnd(); * } * int i = 0; * //while (!Char.IsLetter(asVlastnosti[1], i)) * //{ * // asVlastnosti[0] += asVlastnosti[1][i].ToString(); * // asVlastnosti[1] = asVlastnosti[1].Substring(1); * // //i++; * //} * * i = asVlastnosti[1].Length - 1; * if (i == -1) { * break; * } * while (!Char.IsLetter(asVlastnosti[1], i)) { * if (asVlastnosti[1][i] == ')' || asVlastnosti[1][i] == '-') * break; * asVlastnosti[2] += asVlastnosti[1][i].ToString(); * asVlastnosti[1] = asVlastnosti[1].Substring(0, i); * i--; * if (i == -1) { * break; * } * } * if (i == -1) { * break; * } * sRetrograd = Text.Retrograd(asVlastnosti[1], true); * * if (sRetrograd.IndexOf(" ") > 0 && !(sRetrograd.Contains(" – ") || sRetrograd.Contains(" - "))) { * asVlastnosti[16] = sRetrograd.Substring(sRetrograd.LastIndexOf(" ") + 1); * asVlastnosti[17] = sRetrograd.Substring(0, sRetrograd.LastIndexOf(" ")); * } * else * asVlastnosti[16] = sRetrograd; */ if (sSubVoceId == null) { //sSubVoce = sHeslo; sSubVoceId = hi.Id; } /* * if (sSubVoceId == null) { * //sSubVoce = sHeslo; * sSubVoceId = asVlastnosti[7]; * } */ //if (sType == null) // sType = ""; //sw.WriteLine(String.Join("|", asVlastnosti)); /* * if (hi.HesloveSlovo == "Žižka") { * string sT = hi.HesloveSlovo; * bool b = hi.JeInterni; * } * */ sw.WriteLine(hi.Zaznam()); break; case "heslovaStat": sHeslovaStatTyp = r.GetAttribute("type"); sHeslovaStatID = r.GetAttribute("id"); sSubVoce = r.GetAttribute("defaulthw"); sPouziti = r.GetAttribute("use"); //internal, public sSubVoceId = null; break; case "pismeno": sPismeno = r.GetAttribute("id"); break; case "heslar": sZdroj = r.GetAttribute("dictionary"); break; } } } } } }
public override void gaxb_load(XmlReader reader, object _parent, Hashtable args) { base.gaxb_load(reader, _parent, args); if(reader == null && _parent == null) return; parent = _parent; if(this.GetType() == typeof( PUText )) { gaxb_addToParent(); } //xmlns = reader.GetAttribute("xmlns"); string attr; attr = reader.GetAttribute("font"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { font = attr; } attr = reader.GetAttribute("fontSize"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr == null) { attr = "12"; } if(attr != null) { fontSize = (int)float.Parse(attr); } attr = reader.GetAttribute("fontStyle"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { fontStyle = (PlanetUnity2.FontStyle)Enum.Parse(typeof(PlanetUnity2.FontStyle), attr); } attr = reader.GetAttribute("fontColor"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr == null) { attr = "0,0,0,1"; } if(attr != null) { fontColor = new Color().PUParse(attr); } attr = reader.GetAttribute("lineSpacing"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { lineSpacing = float.Parse(attr); } attr = reader.GetAttribute("alignment"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr == null) { attr = "middleCenter"; } if(attr != null) { alignment = (PlanetUnity2.TextAlignment)Enum.Parse(typeof(PlanetUnity2.TextAlignment), attr); } attr = reader.GetAttribute("value"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { value = attr; } attr = reader.GetAttribute("sizeToFit"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { sizeToFit = bool.Parse(attr); } attr = reader.GetAttribute("maxFontSize"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { maxFontSize = (int)float.Parse(attr); } attr = reader.GetAttribute("minFontSize"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { minFontSize = (int)float.Parse(attr); } attr = reader.GetAttribute("vOverflow"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { vOverflow = bool.Parse(attr); } attr = reader.GetAttribute("hOverflow"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { hOverflow = bool.Parse(attr); } attr = reader.GetAttribute("onLinkClick"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { onLinkClick = attr; } }
/// <summary> /// Rozdělí heslář podle písmen abecedy. Jedno písmeno = jeden soubor. /// </summary> /// <param name="strVstupniSoubor">Vstupní soubor (kompletní heslář ve formátu XML.</param> /// <param name="sVystupniAdresar">Výstoní adresář, do něhož se uloží vygenerované soubory (pro každé písmeno jeden soubor).</param> internal static void RozdelitPodlePismen(string strVstupniSoubor, string sVystupniAdresar) { XmlTextReader treader = new XmlTextReader(strVstupniSoubor); XmlReaderSettings xrs = new XmlReaderSettings(); xrs.ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags.None; XmlReader r = XmlReader.Create(treader, xrs); XmlTextWriter xwPismeno = null; StringBuilder sb = new System.Text.StringBuilder(); bool bPismeno = false; /* * using (XmlReader r = Objekty.VytvorXmlReader(mstrVstupniSoubor)) { * using (XmlWriter xw = Objekty.VytvorXmlWriter(mstrVystupniSoubor)) { * xw.WriteStartDocument(true); * * while (r.Read()) { * if (r.NodeType == XmlNodeType.Element) { * switch (r.Name) { * case "milestone": * break; * default: * Transformace.SerializeNode(r, xw); * break; * * } * } * else if (r.NodeType == XmlNodeType.EndElement) { * switch (r.Name) { * case "milestone": * break; * default: * Transformace.SerializeNode(r, xw); * break; * } * } * else { Transformace.SerializeNode(r, xw); } * * } * * } * } */ #region WHILE while (r.Read()) { if (r.NodeType == XmlNodeType.Element) { #region SWITCH switch (r.Name) { case "pismeno": if (bPismeno) { xwPismeno.WriteEndDocument(); xwPismeno.Flush(); xwPismeno.Close(); } bPismeno = true; string sID = r.GetAttribute("id"); xwPismeno = new XmlTextWriter(sVystupniAdresar + sID + ".xml", System.Text.Encoding.UTF8); xwPismeno.Formatting = Formatting.Indented; xwPismeno.Indentation = 2; xwPismeno.WriteStartDocument(true); Transformace.SerializeNode(r, xwPismeno); break; case "heslovaStat": Transformace.SerializeNode(r, xwPismeno); sb = new System.Text.StringBuilder(); break; case "hw": sb.Append(r.ReadString() + ", "); break; } #endregion } #region IF2 if (r.NodeType == XmlNodeType.EndElement) { switch (r.Name) { case "heslovaStat": sb.Remove(sb.Length - 2, 2); xwPismeno.WriteStartElement("hw"); xwPismeno.WriteString(sb.ToString()); xwPismeno.WriteEndElement(); // hw xwPismeno.WriteEndElement(); // heslovaStat break; case "pismeno": Transformace.SerializeNode(r, xwPismeno); break; } } #endregion } #endregion xwPismeno.WriteEndDocument(); xwPismeno.Close(); xwPismeno = null; }
protected override void DeserializeElement(object obj, XmlReader reader, SerializationContext state) { ListItem listItem; bool isGenericList; MethodInfo methodInfo; System.Collections.IList list; if (obj is System.Collections.IList) { methodInfo = null; isGenericList = false; list = (System.Collections.IList)obj; } else { list = null; isGenericList = true; methodInfo = obj.GetType().GetMethod("Add"); } if (base.CanDeserializeElement(obj, reader, state)) { base.DeserializeElement(obj, reader, state); return; } if (aliasToItemMap.TryGetValue(reader.Name, out listItem)) { if (listItem.Attribute != null && listItem.Attribute.SerializeAsValueNode && listItem.Attribute.ValueNodeAttributeName != null && listItem.Serializer is TypeSerializerWithSimpleTextSupport) { var s = reader.GetAttribute(listItem.Attribute.ValueNodeAttributeName); if (isGenericList) { methodInfo.Invoke(obj, new object[] { ((TypeSerializerWithSimpleTextSupport)listItem.Serializer).Deserialize(s, state) }); } else { list.Add(((TypeSerializerWithSimpleTextSupport)listItem.Serializer).Deserialize(s, state)); } XmlReaderHelper.ReadAndConsumeMatchingEndElement(reader); } else { if (isGenericList) { methodInfo.Invoke(obj, new object[] { listItem.Serializer.Deserialize(reader, state) }); } else { list.Add(listItem.Serializer.Deserialize(reader, state)); } } } else { TypeSerializer serializer = null; if (this.dynamicTypeResolver != null) { var type = dynamicTypeResolver.GetType(reader); if (type != null) { serializer = cache.GetTypeSerializerBySupportedType(type); } } if (serializer == null) { base.DeserializeElement(obj, reader, state); } else { if (isGenericList) { methodInfo.Invoke(obj, new object[] { serializer.Deserialize(reader, state) }); } else { list.Add(serializer.Deserialize(reader, state)); } } } }
protected override void OnReadXml(XmlReader reader) { base.OnReadXml(reader); // This reads only the target node... if (!String.Equals(reader.Name, "TypeTarget", StringComparison.OrdinalIgnoreCase)) { return; } name = reader.GetAttribute("name"); templates = new List <string>(); XmlNodeType nodeType = XmlNodeType.None; while (reader.Read()) { nodeType = reader.NodeType; if (nodeType == XmlNodeType.Element) { // Read the base contents in... if (String.Equals(reader.Name, "Target", StringComparison.OrdinalIgnoreCase)) { base.OnReadXml(reader); } else if (String.Equals(reader.Name, "NamespaceReference", StringComparison.OrdinalIgnoreCase)) { containingNamespace = new NamespaceReference(); containingNamespace.ReadXml(reader); } else if (String.Equals(reader.Name, "SimpleTypeReference", StringComparison.OrdinalIgnoreCase)) { containingType = new SimpleTypeReference(); containingType.ReadXml(reader); } else if (String.Equals(reader.Name, "Templates", StringComparison.OrdinalIgnoreCase)) { while (reader.Read()) { nodeType = reader.NodeType; if (nodeType == XmlNodeType.Element) { if (String.Equals(reader.Name, "Template", StringComparison.OrdinalIgnoreCase)) { templates.Add(reader.GetAttribute("value")); } } else if (nodeType == XmlNodeType.EndElement) { if (String.Equals(reader.Name, "Templates", StringComparison.OrdinalIgnoreCase)) { break; } } } } } else if (nodeType == XmlNodeType.EndElement) { if (String.Equals(reader.Name, "TypeTarget", StringComparison.OrdinalIgnoreCase)) { break; } } } }
// Read and extract into Element class each attribut of node name "element" Element check_attribute_element(XmlReader xml_reader, Element element) { if (xml_reader.HasAttributes) { while (xml_reader.MoveToNextAttribute() != false) { string prefab_name = ""; if ((prefab_name = xml_reader.GetAttribute("prefab")) != null) { if (Resources.Load(prefab_name) != null) element.prefab = Resources.Load(prefab_name) as GameObject; } } } return element; }
public void ReadXml(XmlReader reader) { Type = (TileType)int.Parse(reader.GetAttribute("Type")); }
public override void gaxb_load(XmlReader reader, object _parent, Hashtable args) { base.gaxb_load(reader, _parent, args); if(reader == null && _parent == null) return; parent = _parent; if(this.GetType() == typeof( PUNotification )) { gaxb_addToParent(); } //xmlns = reader.GetAttribute("xmlns"); string attr; attr = reader.GetAttribute("name"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { name = attr; } }
private static void CopyXmlToWriter(XmlReader r, XmlWriter w) { while (r.Read()) { switch (r.NodeType) { case XmlNodeType.Element: w.WriteStartElement(r.Prefix, r.LocalName, r.NamespaceURI); if (r.HasAttributes) { r.MoveToFirstAttribute(); do { if (r.LocalName == "xop" && r.Prefix == "xmlns" && r.Value == "http://www.w3.org/2004/08/xop/include") { // special case: do not need to rewrite the xmlns:xop for MTOM // skip } else { w.WriteAttributeString(r.Prefix, r.LocalName, r.NamespaceURI, r.Value); } } while (r.MoveToNextAttribute()); r.MoveToElement(); } if (r.IsEmptyElement) { w.WriteEndElement(); } break; case XmlNodeType.CDATA: w.WriteCData(r.Value); break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: w.WriteWhitespace(r.Value); break; case XmlNodeType.Text: w.WriteString(r.Value); break; case XmlNodeType.XmlDeclaration: string stdAlone = r.GetAttribute("standalone"); if (stdAlone == null) { w.WriteStartDocument(); } else { bool isStandAlone = false; if (bool.TryParse(stdAlone, out isStandAlone)) { w.WriteStartDocument(isStandAlone); } else { w.WriteStartDocument(); } } break; case XmlNodeType.Comment: w.WriteComment(r.Value); break; case XmlNodeType.EndElement: w.WriteFullEndElement(); break; } } }
public StackPanel( CreateParams parentParams, XmlReader reader ) { Initialize( ); // Always get our style first mStyle = parentParams.Style; Styles.Style.ParseStyleAttributesWithDefaults( reader, ref mStyle, ref ControlStyles.mStackPanel ); // check for attributes we support RectangleF bounds = new RectangleF( ); SizeF parentSize = new SizeF( parentParams.Width, parentParams.Height ); ParseCommonAttribs( reader, ref parentSize, ref bounds ); // Get margins and padding RectangleF padding; RectangleF margin; GetMarginsAndPadding( ref mStyle, ref parentSize, ref bounds, out margin, out padding ); // apply margins to as much of the bounds as we can (bottom must be done by our parent container) ApplyImmediateMargins( ref bounds, ref margin, ref parentSize ); Margin = margin; // check for border styling int borderPaddingPx = 0; if ( mStyle.mBorderColor.HasValue ) { BorderView.BorderColor = mStyle.mBorderColor.Value; } if( mStyle.mBorderRadius.HasValue ) { BorderView.CornerRadius = mStyle.mBorderRadius.Value; } if( mStyle.mBorderWidth.HasValue ) { BorderView.BorderWidth = mStyle.mBorderWidth.Value; borderPaddingPx = (int)Rock.Mobile.Graphics.Util.UnitToPx( mStyle.mBorderWidth.Value + PrivateNoteConfig.BorderPadding ); } if( mStyle.mBackgroundColor.HasValue ) { BorderView.BackgroundColor = mStyle.mBackgroundColor.Value; } // // now calculate the available width based on padding. (Don't actually change our width) float availableWidth = bounds.Width - padding.Left - padding.Width - (borderPaddingPx * 2); // now read what our children's alignment should be // check for alignment string result = reader.GetAttribute( "ChildAlignment" ); if( string.IsNullOrEmpty( result ) == false ) { switch( result ) { case "Left": { ChildHorzAlignment = Alignment.Left; break; } case "Right": { ChildHorzAlignment = Alignment.Right; break; } case "Center": { ChildHorzAlignment = Alignment.Center; break; } default: { ChildHorzAlignment = mStyle.mAlignment.Value; break; } } } else { // if it wasn't specified, use left alignment. ChildHorzAlignment = Alignment.Left; } // Parse Child Controls bool finishedParsing = false; while( finishedParsing == false && reader.Read( ) ) { switch( reader.NodeType ) { case XmlNodeType.Element: { // let each child have our available width. Style style = new Style( ); style = mStyle; style.mAlignment = ChildHorzAlignment; IUIControl control = Parser.TryParseControl( new CreateParams( this, availableWidth, parentParams.Height, ref style ), reader ); if( control != null ) { ChildControls.Add( control ); } break; } case XmlNodeType.EndElement: { // if we hit the end of our label, we're done. //if( reader.Name == "StackPanel" || reader.Name == "SP" ) if( ElementTagMatches( reader.Name ) ) { finishedParsing = true; } break; } } } LayoutStackPanel( bounds, padding.Left, padding.Top, availableWidth, padding.Height, borderPaddingPx ); }
private void LoadProcess(XmlReader reader) { Lua.Parse(reader.GetAttribute("FilePath")); rootProcess = reader.GetAttribute("FunctionName"); }
public override void gaxb_load(XmlReader reader, object _parent, Hashtable args) { base.gaxb_load(reader, _parent, args); if(reader == null && _parent == null) return; parent = _parent; if(this.GetType() == typeof( PUTable )) { gaxb_addToParent(); } xmlns = reader.GetAttribute("xmlns"); }
/// <summary> /// extract base orchestration Module properties - ServiceModel, Core, etc. /// This is done at this level instead of the base object due to the fact that we have to pull things out of the base orch at the top level, instead of at the /// XmlNode level, which is done from ServiceDeclaration level on down /// </summary> private void GetModuleProperties() { try { #if reader _reader.MoveToContent(); _majVersion = Convert.ToSByte(_reader.GetAttribute("MajorVersion")); _minVersion = Convert.ToSByte(_reader.GetAttribute("MinorVersion")); _core = new Guid(_reader.GetAttribute("Core")); _scheduleModel = new Guid(_reader.GetAttribute("ScheduleModel")); //"inner" properties (Module) _reader.ReadToDescendant("om:Element"); _oid = new Guid(_reader.GetAttribute("OID")); while (_reader.Read()) { if (!_reader.HasAttributes) break; if (_reader.Name.Equals("om:Property")) GetReaderProperties(_reader.GetAttribute("Name"), _reader.GetAttribute("Value")); else if (_reader.Name.Equals("om:Element")) { if (_reader.GetAttribute("Type").Equals("PortType")) _portTypes.Add(new BtsPortType(_reader.ReadSubtree())); else if (_reader.GetAttribute("Type").Equals("PrintElement")) { XmlReader r = _reader.ReadSubtree(); r.Read(); r.Close(); } else if (_reader.GetAttribute("Type").Equals("ServiceDeclaration")) _svcDeclaration = new BtsServiceDeclaration(_reader.ReadSubtree()); else if (_reader.GetAttribute("Type").Equals("MultipartMessageType")) _mmmsgTypes.Add(new BtsMultiPartMessageType(_reader.ReadSubtree())); else if (_reader.GetAttribute("Type").Equals("CorrelationType")) _corrTypes.Add(new BtsCorrelationType(_reader.ReadSubtree())); else if (_reader.GetAttribute("Type").Equals("ServiceLinkType")) _svcLinkTypes.Add(new BtsServiceLinkType(_reader.ReadSubtree())); else if (_reader.GetAttribute("Type").Equals("TargetXMLNamespaceAttribute")) _xmlAttribute = new BtsTargetXmlAttribute(_reader.ReadSubtree()); else if (_reader.GetAttribute("Type").Equals("MethodMessageType")) _msgTypes.Add(new BtsMethodMessageType(_reader.ReadSubtree())); else { Debug.WriteLine("[BtsOrch.GetModuleProperties] unhandled element " + _reader.GetAttribute("Type") + " received (needs implementation)"); Debugger.Break(); } } else continue; //what else could we possibly expect?? } #endif } catch (Exception) { #if DEBUG Debugger.Break(); #endif } }
public override void gaxb_load(XmlReader reader, object _parent, Hashtable args) { base.gaxb_load(reader, _parent, args); if(reader == null && _parent == null) return; parent = _parent; if(this.GetType() == typeof( PUSprite )) { gaxb_addToParent(); } xmlns = reader.GetAttribute("xmlns"); string attr; attr = reader.GetAttribute("resourcePath"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr != null) { resourcePath = attr; resourcePathExists = true; } attr = reader.GetAttribute("position"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr != null) { position = attr; positionExists = true; } attr = reader.GetAttribute("scale"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr != null) { scale = float.Parse(attr); scaleExists = true; } }
private void ReadModel() { SegmentInfo segment = new SegmentInfo(); string attFrom = _xmlReader.GetAttribute("node-from"); if (attFrom == null) { throw new XmlException("Attribute 'from' is missing."); } segment.NodeFromID = int.Parse(attFrom); string attTo = _xmlReader.GetAttribute("node-to"); if (attTo == null) { throw new XmlException("Attribute 'to' is missing."); } segment.NodeToID = int.Parse(attTo); string attWay = _xmlReader.GetAttribute("way"); if (attFrom == null) { throw new XmlException("Attribute 'way' is missing."); } segment.WayID = int.Parse(attWay); Model model = new Model(); model.Segment = segment; string attFreeFlow = _xmlReader.GetAttribute("freeflow"); if (attFreeFlow == null) { throw new XmlException("Attribute 'freeflow' is missing."); } model.FreeFlowTravelTime = double.Parse(attFreeFlow, System.Globalization.CultureInfo.InvariantCulture); string attAvgDelay = _xmlReader.GetAttribute("avg-delay"); if (attAvgDelay == null) { throw new XmlException("Attribute 'avg-delay' is missing."); } model.AvgDelay = double.Parse(attAvgDelay, System.Globalization.CultureInfo.InvariantCulture); string attSignalsDelay = _xmlReader.GetAttribute("signals-delay"); string attSignalProbability = _xmlReader.GetAttribute("signals-prob"); if (attSignalsDelay != null && attSignalProbability != null) { model.TrafficSignalsDelay = new TrafficSignalsDelayInfo() { Length = double.Parse(attSignalsDelay, System.Globalization.CultureInfo.InvariantCulture), Probability = double.Parse(attSignalProbability, System.Globalization.CultureInfo.InvariantCulture) } } ; if (false == _xmlReader.IsEmptyElement) { _xmlReader.Read(); while (_xmlReader.NodeType != XmlNodeType.EndElement) { switch (_xmlReader.NodeType) { case XmlNodeType.Element: switch (_xmlReader.Name) { case "traffic-delay": model.TrafficDelay.Add(ReadTrafficDelay()); continue; default: _xmlReader.Skip(); continue; } default: _xmlReader.Skip(); break; } } } _storage.Add(segment, model); _xmlReader.Skip(); }
public static void ParseBounds( XmlReader reader, ref SizeF parentSize, ref RectangleF bounds ) { // first check without the Margin prefix. string result = reader.GetAttribute( "Left" ); if( string.IsNullOrEmpty( result ) == false ) { bounds.X = ParsePositioningValue( result ); } result = reader.GetAttribute( "Top" ); if( string.IsNullOrEmpty( result ) == false ) { bounds.Y = ParsePositioningValue( result ); } //TODO: Support Right, Bottom // Get width/height result = reader.GetAttribute( "Width" ); if( string.IsNullOrEmpty( result ) == false ) { bounds.Width = ParsePositioningValue( result ); } result = reader.GetAttribute( "Height" ); if( string.IsNullOrEmpty( result ) == false ) { bounds.Height = ParsePositioningValue( result ); } // Convert percentages to whole values if( bounds.X < 1 ) { bounds.X = parentSize.Width * bounds.X; } if( bounds.Y < 1 ) { bounds.Y = parentSize.Height * bounds.Y; } if( bounds.Width < 1 ) { bounds.Width = Math.Max( 1, parentSize.Width - bounds.X ) * bounds.Width; if( bounds.Width == 0 ) { // if 0, just take the our parents width bounds.Width = Math.Max( 1, parentSize.Width - bounds.X ); } } if( bounds.Height < 1 ) { bounds.Height = Math.Max( 1, parentSize.Height - bounds.Y ) * bounds.Height; if( bounds.Height == 0 ) { // if 0, just take the our parents width bounds.Height = Math.Max( 1, parentSize.Height - bounds.Y ); } } }
static void readXML(string filename) { XmlReader reader = XmlReader.Create(filename); while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "Goal": string goalId = reader.GetAttribute("id"); reader.MoveToAttribute("priority"); int goalPriority = reader.ReadContentAsInt(); Dictionary <string, bool> goalConditions = new Dictionary <string, bool>(); while (reader.Read()) { if (reader.IsEmptyElement) { //read condition tags reader.MoveToFirstAttribute(); string conditionID = reader.Name; bool conditionValue = reader.ReadContentAsBoolean(); goalConditions.Add(conditionID, conditionValue); } if (reader.NodeType == XmlNodeType.EndElement) { break; } } planner.createGoal(goalId, goalConditions, goalPriority); break; case "Scene": string sceneId = reader.GetAttribute("id"); string sceneOutput = "<NO OUTPUT>"; Dictionary <string, bool> preconditions = new Dictionary <string, bool>(); Dictionary <string, Dictionary <string, bool> > outcomes = new Dictionary <string, Dictionary <string, bool> >(); while (reader.Read()) { if (reader.IsStartElement("Output")) { sceneOutput = reader.ReadElementContentAsString(); continue; } if (reader.IsEmptyElement) { //read condition tags reader.MoveToFirstAttribute(); string conditionID = reader.Name; bool conditionValue = reader.ReadContentAsBoolean(); preconditions.Add(conditionID, conditionValue); } if (reader.IsStartElement("Outcome")) { //read outcome tags string outComeId = reader.GetAttribute("id"); Dictionary <string, bool> effects = new Dictionary <string, bool>(); while (reader.Read()) { if (reader.IsEmptyElement) { //read effect tags reader.MoveToFirstAttribute(); string effectID = reader.Name; bool effectValue = reader.ReadContentAsBoolean(); effects.Add(effectID, effectValue); } if (reader.NodeType == XmlNodeType.EndElement) { break; } } reader.Read(); effects.Add("SceneIsDone" + sceneId, true); //make sure outcomes disable the whole scene outcomes.Add(outComeId, effects); } if (reader.NodeType == XmlNodeType.EndElement) { break; } } preconditions.Add("SceneIsDone" + sceneId, false); possibleScenes.Add(new Scene(sceneId, sceneOutput, preconditions, outcomes)); break; case "StartState": Dictionary <string, bool> startState = new Dictionary <string, bool>(); while (reader.Read()) { if (reader.IsEmptyElement) { //read condition tags reader.MoveToFirstAttribute(); string conditionID = reader.Name; bool conditionValue = reader.ReadContentAsBoolean(); startState.Add(conditionID, conditionValue); } if (reader.NodeType == XmlNodeType.EndElement) { break; } } planner.createStartState(startState); break; } } } reader.Close(); }
public override void gaxb_load(XmlReader reader, object _parent, Hashtable args) { base.gaxb_load(reader, _parent, args); if(reader == null && _parent == null) return; parent = _parent; if(this.GetType() == typeof( PUGridLayoutGroup )) { gaxb_addToParent(); } //xmlns = reader.GetAttribute("xmlns"); string attr; attr = reader.GetAttribute("cellSize"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr == null) { attr = "100,100"; } if(attr != null) { cellSize = new Vector2().PUParse(attr); } attr = reader.GetAttribute("spacing"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr == null) { attr = "0,0"; } if(attr != null) { spacing = new Vector2().PUParse(attr); } attr = reader.GetAttribute("startCorner"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { startCorner = (PlanetUnity2.GridLayoutStartCorner)Enum.Parse(typeof(PlanetUnity2.GridLayoutStartCorner), attr); } attr = reader.GetAttribute("startAxis"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { startAxis = (PlanetUnity2.GridLayoutStartAxis)Enum.Parse(typeof(PlanetUnity2.GridLayoutStartAxis), attr); } attr = reader.GetAttribute("childAlignment"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { childAlignment = (PlanetUnity2.GridLayoutChildAlignment)Enum.Parse(typeof(PlanetUnity2.GridLayoutChildAlignment), attr); } attr = reader.GetAttribute("fixedRows"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { fixedRows = (int)float.Parse(attr); } attr = reader.GetAttribute("fixedColumns"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { fixedColumns = (int)float.Parse(attr); } }
public override void gaxb_load(XmlReader reader, object _parent, Hashtable args) { base.gaxb_load(reader, _parent, args); if(reader == null && _parent == null) return; parent = _parent; if(this.GetType() == typeof( PUGameObject )) { gaxb_addToParent(); } xmlns = reader.GetAttribute("xmlns"); string attr; attr = reader.GetAttribute("bounds"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr != null) { bounds = attr; boundsExists = true; } attr = reader.GetAttribute("rotation"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr != null) { rotation = attr; rotationExists = true; } attr = reader.GetAttribute("hidden"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr != null) { hidden = bool.Parse(attr); hiddenExists = true; } attr = reader.GetAttribute("lastY"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr != null) { lastY = float.Parse(attr); lastYExists = true; } attr = reader.GetAttribute("lastX"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr != null) { lastX = float.Parse(attr); lastXExists = true; } attr = reader.GetAttribute("renderQueueOffset"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr != null) { renderQueueOffset = int.Parse(attr); renderQueueOffsetExists = true; } attr = reader.GetAttribute("clipDepth"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr == null) { attr = "false"; } if(attr != null) { clipDepth = bool.Parse(attr); clipDepthExists = true; } attr = reader.GetAttribute("clipStencil"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr == null) { attr = "false"; } if(attr != null) { clipStencil = bool.Parse(attr); clipStencilExists = true; } }
public override void gaxb_load(XmlReader reader, object _parent, Hashtable args) { base.gaxb_load(reader, _parent, args); if(reader == null && _parent == null) return; parent = _parent; if(this.GetType() == typeof( PUCode )) { gaxb_addToParent(); } //xmlns = reader.GetAttribute("xmlns"); string attr; attr = reader.GetAttribute("class"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { _class = attr; } attr = reader.GetAttribute("singleton"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr == null) { attr = "false"; } if(attr != null) { singleton = bool.Parse(attr); } }
public static TextFrame ReadXml(XmlReader reader) { TextFrame tf = new TextFrame(); if (reader.HasAttributes) { tf.Self = System.Convert.ToString(reader.GetAttribute("Self")); tf.ParentStory = System.Convert.ToString(reader.GetAttribute("ParentStory")); tf.PreviousTextFrame = System.Convert.ToString(reader.GetAttribute("PreviousTextFrame")); tf.NextTextFrame = System.Convert.ToString(reader.GetAttribute("NextTextFrame")); tf.ContentType = (ContentType)Enum.Parse(typeof(ContentType), reader.GetAttribute("ContentType")); tf.StrokeWeight = Parser.ParseDouble(reader.GetAttribute("StrokeWeight")); tf.GradientFillStart = new UnitPointType(reader.GetAttribute("GradientFillStart")); tf.GradientFillLength = Parser.ParseDouble(reader.GetAttribute("GradientFillLength")); tf.GradientFillAngle = Parser.ParseDouble(reader.GetAttribute("GradientFillAngle")); tf.GradientStrokeStart = new UnitPointType(reader.GetAttribute("GradientStrokeStart")); tf.GradientStrokeLength = Parser.ParseDouble(reader.GetAttribute("GradientStrokeLength")); tf.GradientStrokeAngle = Parser.ParseDouble(reader.GetAttribute("GradientStrokeAngle")); tf.ItemLayer = System.Convert.ToString(reader.GetAttribute("ItemLayer")); tf.Locked = Parser.ParseBoolean(reader.GetAttribute("Locked")); tf.LocalDisplaySetting = (DisplaySettingOptions?)Parser.ParseEnum <DisplaySettingOptions>(reader.GetAttribute("LocalDisplaySetting")); tf.GradientFillHiliteLength = Parser.ParseDouble(reader.GetAttribute("GradientFillHiliteLength")); tf.GradientFillHiliteAngle = Parser.ParseDouble(reader.GetAttribute("GradientFillHiliteAngle")); tf.GradientStrokeHiliteLength = Parser.ParseDouble(reader.GetAttribute("GradientStrokeHiliteLength")); tf.GradientStrokeHiliteAngle = Parser.ParseDouble(reader.GetAttribute("GradientStrokeHiliteAngle")); tf.AppliedObjectStyle = System.Convert.ToString(reader.GetAttribute("AppliedObjectStyle")); tf.Visible = Parser.ParseBoolean(reader.GetAttribute("Visible")); tf.Name = System.Convert.ToString(reader.GetAttribute("Name")); tf.ItemTransform = System.Convert.ToString(reader.GetAttribute("ItemTransform")); } if (reader.IsEmptyElement) { return(tf); } while (reader.Read()) { if ((string)reader.Name == "Properties") { while (reader.Read()) { if ((string)reader.Name == "PathGeometry") { tf.PathGeometry = PathGeometry.ReadXml(reader); } else if ((string)reader.Name == "Properties") { if (reader.NodeType == XmlNodeType.EndElement) { break; } } else { if (reader.NodeType == XmlNodeType.Element) { Debug.WriteLine("Unrecognized element: {0} in element: {1}", reader.Name, "TextFrame - Properties"); } } } } else if ((string)reader.Name == "TextFramePreference") { tf.TextFramePreference = TextFramePreference.ReadXml(reader); } else if ((string)reader.Name == "TextWrapPreference") { tf.TextWrapPreference = TextWrapPreference.ReadXml(reader); } else if ((string)reader.Name == "TextFrame") { if (reader.NodeType == XmlNodeType.EndElement) { break; } } else { if (reader.NodeType == XmlNodeType.Element) { Debug.WriteLine("Unrecognized element: {0} in element: {1}", reader.Name, "TextFrame"); } } } return(tf); }
public override void gaxb_load(XmlReader reader, object _parent, Hashtable args) { base.gaxb_load(reader, _parent, args); if(reader == null && _parent == null) return; parent = _parent; if(this.GetType() == typeof( PUCode )) { gaxb_addToParent(); } xmlns = reader.GetAttribute("xmlns"); string attr; attr = reader.GetAttribute("class"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr != null) { _class = attr; _classExists = true; } attr = reader.GetAttribute("singleton"); if(attr != null && planetOverride != null) { attr = processStringMethod.Invoke(null, new [] {_parent, attr}).ToString(); } if(attr == null) { attr = "false"; } if(attr != null) { singleton = bool.Parse(attr); singletonExists = true; } }
static void Main() { String strExePath = System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName; ExeDir = strExePath.Substring(0, strExePath.LastIndexOf('\\') + 1); //ContractSelector.LoadGraphicsResources(); //ContractSelector.SetCoordinates(); // ------------------ start: XML ------------------ if (System.IO.File.Exists(Program.ExeDir + "BridgeNote.xml") == false) { MessageBox.Show("Не найден файл BridgeNote.xml!", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } String strDBPath = ""; String strTempDir = ""; String strDBPath_final = ""; String strTempDir_final = ""; bool absDBPath = true; bool absTempDir = true; bool useTempDir = false; XmlReaderSettings xml_settings = new XmlReaderSettings(); xml_settings.ConformanceLevel = ConformanceLevel.Fragment; xml_settings.IgnoreWhitespace = true; xml_settings.IgnoreComments = true; XmlParserContext xml_context = new XmlParserContext(null, null, null, XmlSpace.Default, System.Text.Encoding.Default); XmlReader xml_reader = null; try { xml_reader = XmlReader.Create(Program.ExeDir + "BridgeNote.xml", xml_settings, xml_context); xml_reader.Read(); xml_reader.ReadStartElement("Settings"); xml_reader.ReadStartElement("Database"); if (xml_reader.IsStartElement("File")) { strDBPath = xml_reader.GetAttribute("path"); if (strDBPath == null || strDBPath.Length == 0) { xml_reader.Close(); MessageBox.Show("Не указан путь к файлу БД!", "BridgeNote.xml", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } try { absDBPath = bool.Parse(xml_reader.GetAttribute("absolute")); } catch (Exception e) { xml_reader.Close(); MessageBox.Show("Ошибка в Settings.Database.File.absolute:\n" + e.Message, "BridgeNote.xml", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } } else { xml_reader.Close(); MessageBox.Show("Не найден тег File!", "BridgeNote.xml", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } xml_reader.Skip(); if (xml_reader.IsStartElement("TempDir")) { try { useTempDir = bool.Parse(xml_reader.GetAttribute("use")); } catch (Exception e) { xml_reader.Close(); MessageBox.Show("Ошибка в Settings.Database.TempDir.use:\n" + e.Message, "BridgeNote.xml", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } try { absTempDir = bool.Parse(xml_reader.GetAttribute("absolute")); } catch (Exception e) { xml_reader.Close(); MessageBox.Show("Ошибка в Settings.Database.TempDir.absolute:\n" + e.Message, "BridgeNote.xml", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } strTempDir = xml_reader.GetAttribute("path"); if (useTempDir && (strTempDir == null || absTempDir && strTempDir.Length == 0)) { xml_reader.Close(); MessageBox.Show("Не указана временная папка для БД!", "BridgeNote.xml", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } } else { xml_reader.Close(); MessageBox.Show("Не найден тег TempDir!", "BridgeNote.xml", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } xml_reader.Skip(); xml_reader.ReadEndElement(); xml_reader.ReadEndElement(); } catch (XmlException e) { if (xml_reader != null) { xml_reader.Close(); } MessageBox.Show(e.Message, "BridgeNote.xml", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } xml_reader.Close(); // ------------------ end: XML ------------------ strDBPath_final = (absDBPath ? strDBPath : (Program.ExeDir + strDBPath)); strTempDir_final = (useTempDir ? (absTempDir ? strTempDir : (Program.ExeDir + strTempDir)) : ""); // Проверить временную папку if (useTempDir && System.IO.Directory.Exists(strTempDir_final) == false) { MessageBox.Show("Неправильно указана временная папка для БД!", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); return; } // Инициализировать строку подключения DB.InitializeConnectionString(strDBPath_final, strTempDir_final); // Создать БД, если нужно if (System.IO.File.Exists(strDBPath_final) == false) { if (MessageBox.Show("База данных не найдена!\nСоздать новую БД и проинициализировать ее?", "db create", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { if (DB.CreateDatabase(strDBPath_final) == false) { return; } DB.CreateTables(false); DB.Disconnect(); } else { return; } } // Подключиться к базе данных DB.ReConnect(); // Следить за подключением DB.sqlConnection.StateChange += new StateChangeEventHandler(sqlConnection_StateChange); // Запуск главной формы, большой try-catch если DEBUG #if DEBUG try { Application.Run(MainForm = new Form1()); } catch (Exception e) { System.IO.StreamWriter sw = System.IO.File.AppendText(Program.ExeDir + "debug.txt"); sw.Write(DateTime.Now.ToString() + "\n"); sw.Write(e.Message + "\n"); sw.Write(e.StackTrace + "\n"); if (e.GetType() == typeof(System.Data.SqlServerCe.SqlCeException)) { System.Data.SqlServerCe.SqlCeException ex = (System.Data.SqlServerCe.SqlCeException)e; sw.Write("[SQL] NativeError = " + ex.NativeError + "\n"); for (int i = 0; i < ex.Errors.Count; i++) { sw.Write("[SQL_err_" + i + "] " + ex.Errors[i].Message + " * " + ex.Errors[i].NativeError + "\n"); } } sw.Write("-------------" + "\n"); sw.Close(); throw; } #else Application.Run(MainForm = new Form1()); #endif }
/// <summary> /// Read header information /// </summary> /// <param name="reader">XmlReader to use to parse the header</param> /// <param name="keep">True if full pathnames are to be kept, false otherwise (default)</param> private void ReadHeader(XmlReader reader, bool keep) { bool superdat = false; // If there's no subtree to the header, skip it if (reader == null) { return; } // Otherwise, add what is possible reader.MoveToContent(); while (!reader.EOF) { // We only want elements if (reader.NodeType != XmlNodeType.Element || reader.Name == "header") { reader.Read(); continue; } // Get all header items (ONLY OVERWRITE IF THERE'S NO DATA) string content; switch (reader.Name) { case "name": content = reader.ReadElementContentAsString(); Header.Name = Header.Name ?? content; superdat = superdat || content.Contains(" - SuperDAT"); if (keep && superdat) { Header.Type = Header.Type ?? "SuperDAT"; } break; case "description": content = reader.ReadElementContentAsString(); Header.Description = Header.Description ?? content; break; case "rootdir": // This is exclusive to TruRip XML content = reader.ReadElementContentAsString(); Header.RootDir = Header.RootDir ?? content; break; case "category": content = reader.ReadElementContentAsString(); Header.Category = Header.Category ?? content; break; case "version": content = reader.ReadElementContentAsString(); Header.Version = Header.Version ?? content; break; case "date": content = reader.ReadElementContentAsString(); Header.Date = Header.Date ?? content.Replace(".", "/"); break; case "author": content = reader.ReadElementContentAsString(); Header.Author = Header.Author ?? content; break; case "email": content = reader.ReadElementContentAsString(); Header.Email = Header.Email ?? content; break; case "homepage": content = reader.ReadElementContentAsString(); Header.Homepage = Header.Homepage ?? content; break; case "url": content = reader.ReadElementContentAsString(); Header.Url = Header.Url ?? content; break; case "comment": content = reader.ReadElementContentAsString(); Header.Comment = (Header.Comment ?? content); break; case "type": // This is exclusive to TruRip XML content = reader.ReadElementContentAsString(); Header.Type = Header.Type ?? content; superdat = superdat || content.Contains("SuperDAT"); break; case "clrmamepro": if (Header.HeaderSkipper == null) { Header.HeaderSkipper = reader.GetAttribute("header"); } if (Header.ForceMerging == MergingFlag.None) { Header.ForceMerging = reader.GetAttribute("forcemerging").AsMergingFlag(); } if (Header.ForceNodump == NodumpFlag.None) { Header.ForceNodump = reader.GetAttribute("forcenodump").AsNodumpFlag(); } if (Header.ForcePacking == PackingFlag.None) { Header.ForcePacking = reader.GetAttribute("forcepacking").AsPackingFlag(); } reader.Read(); break; case "romcenter": if (Header.System == null) { Header.System = reader.GetAttribute("plugin"); } if (Header.RomMode == MergingFlag.None) { Header.RomMode = reader.GetAttribute("rommode").AsMergingFlag(); } if (Header.BiosMode == MergingFlag.None) { Header.BiosMode = reader.GetAttribute("biosmode").AsMergingFlag(); } if (Header.SampleMode == MergingFlag.None) { Header.SampleMode = reader.GetAttribute("samplemode").AsMergingFlag(); } if (Header.LockRomMode == null) { Header.LockRomMode = reader.GetAttribute("lockrommode").AsYesNo(); } if (Header.LockBiosMode == null) { Header.LockBiosMode = reader.GetAttribute("lockbiosmode").AsYesNo(); } if (Header.LockSampleMode == null) { Header.LockSampleMode = reader.GetAttribute("locksamplemode").AsYesNo(); } reader.Read(); break; default: reader.Read(); break; } } }
private void parseNode() { Node node = new Node(); node.id = long.Parse(_reader.GetAttribute("id")); node.latitude = float.Parse(_reader.GetAttribute("lat")); node.longitude = float.Parse(_reader.GetAttribute("lon")); _currentElement = node; AddNode(node); }
static void AddElementToList(string in_currentPathInProj, XmlReader in_reader, AssetType in_type, LinkedList<AkWwiseProjectData.PathElement> in_pathAndIcons, int in_wwuIndex) { if (in_type.RootDirectoryName == "Events" || in_type.RootDirectoryName == "Master-Mixer Hierarchy" || in_type.RootDirectoryName == "SoundBanks") { AkWwiseProjectData.Event valueToAdd = new AkWwiseProjectData.Event(); valueToAdd.Name = in_reader.GetAttribute("Name"); valueToAdd.Guid = new Guid(in_reader.GetAttribute("ID")).ToByteArray(); valueToAdd.ID = (int)AkUtilities.ShortIDGenerator.Compute(valueToAdd.Name); valueToAdd.Path = in_type.RootDirectoryName == "Master-Mixer Hierarchy" ? in_currentPathInProj : Path.Combine(in_currentPathInProj, valueToAdd.Name); valueToAdd.PathAndIcons = new List<AkWwiseProjectData.PathElement>(in_pathAndIcons); if (in_type.RootDirectoryName == "Events") { valueToAdd.PathAndIcons.Add(new AkWwiseProjectData.PathElement(valueToAdd.Name, AkWwiseProjectData.WwiseObjectType.EVENT)); AkWwiseProjectInfo.GetData().EventWwu[in_wwuIndex].List.Add(valueToAdd); } else if (in_type.RootDirectoryName == "SoundBanks") { valueToAdd.PathAndIcons.Add(new AkWwiseProjectData.PathElement(valueToAdd.Name, AkWwiseProjectData.WwiseObjectType.SOUNDBANK)); AkWwiseProjectInfo.GetData().BankWwu[in_wwuIndex].List.Add(valueToAdd); } else { AkWwiseProjectInfo.GetData().AuxBusWwu[in_wwuIndex].List.Add(valueToAdd); } in_reader.Read(); } else if (in_type.RootDirectoryName == "States" || in_type.RootDirectoryName == "Switches") { var XmlElement = XNode.ReadFrom(in_reader) as XElement; AkWwiseProjectData.GroupValue valueToAdd = new AkWwiseProjectData.GroupValue(); AkWwiseProjectData.WwiseObjectType SubElemIcon; valueToAdd.Name = XmlElement.Attribute("Name").Value; valueToAdd.Guid = new Guid(XmlElement.Attribute("ID").Value).ToByteArray(); valueToAdd.ID = (int)AkUtilities.ShortIDGenerator.Compute(valueToAdd.Name); valueToAdd.Path = Path.Combine(in_currentPathInProj, valueToAdd.Name); valueToAdd.PathAndIcons = new List<AkWwiseProjectData.PathElement>(in_pathAndIcons); if (in_type.RootDirectoryName == "States") { SubElemIcon = AkWwiseProjectData.WwiseObjectType.STATE; valueToAdd.PathAndIcons.Add(new AkWwiseProjectData.PathElement(valueToAdd.Name, AkWwiseProjectData.WwiseObjectType.STATEGROUP)); } else { SubElemIcon = AkWwiseProjectData.WwiseObjectType.SWITCH; valueToAdd.PathAndIcons.Add(new AkWwiseProjectData.PathElement(valueToAdd.Name, AkWwiseProjectData.WwiseObjectType.SWITCHGROUP)); } XName ChildrenList = XName.Get("ChildrenList"); XName ChildElem = XName.Get(in_type.ChildElementName); XElement ChildrenElement = XmlElement.Element(ChildrenList); if (ChildrenElement != null) { foreach (var element in ChildrenElement.Elements(ChildElem)) { if (element.Name == in_type.ChildElementName) { string elementName = element.Attribute("Name").Value; valueToAdd.values.Add(elementName); valueToAdd.ValueGuids.Add(new AkWwiseProjectData.ByteArrayWrapper( new Guid(element.Attribute("ID").Value).ToByteArray())); valueToAdd.valueIDs.Add((int)AkUtilities.ShortIDGenerator.Compute(elementName)); valueToAdd.ValueIcons.Add(new AkWwiseProjectData.PathElement(elementName, SubElemIcon)); } } } if (in_type.RootDirectoryName == "States") { AkWwiseProjectInfo.GetData().StateWwu[in_wwuIndex].List.Add(valueToAdd); } else { AkWwiseProjectInfo.GetData().SwitchWwu[in_wwuIndex].List.Add(valueToAdd); } } else { Debug.LogError("WwiseUnity: Unknown asset type in WWU parser"); } }
protected void InternalReadXml(XmlReader r) { string containingElementType = ""; MemberInfo[] fields = GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic); bool skipCloseElement = false; foreach (MemberInfo f in fields) { var mInfo = Globs.GetAttr <MarshalAsAttribute>(f); var elementType = Globs.GetMemberType(f); string elementName = f.Name.TrimStart(new[] { '_' }); if (r.HasAttributes) { containingElementType = r.GetAttribute("type"); } r.ReadStartElement(elementName); string s; Object val; switch (mInfo.MarshType) { case MarshalType.UnionSelector: s = r.ReadContentAsString(); // ReSharper disable once AssignNullToNotNullAttribute val = Enum.Parse(elementType, s); Globs.SetMember(f, this, val); break; case MarshalType.ArrayCount: int intVal = r.ReadContentAsInt(); // ReSharper disable once AssignNullToNotNullAttribute val = Convert.ChangeType(intVal, elementType); Globs.SetMember(f, this, val); break; case MarshalType.Normal: // ReSharper disable once PossibleNullReferenceException if (elementType.GetTypeInfo().IsSubclassOf(typeof(TpmStructureBase))) { val = Activator.CreateInstance(elementType); Globs.SetMember(f, this, val); ((TpmStructureBase)val).InternalReadXml(r); break; } // ReSharper disable once RedundantIfElseBlock else { if (elementType.TypeIsEnum()) { s = r.ReadContentAsString(); val = Enum.Parse(elementType, s); Globs.SetMember(f, this, val); break; } if (elementType == typeof(uint) || elementType == typeof(ushort) || elementType == typeof(byte)) { // TODO: This should be unsigned long longVal = r.ReadContentAsLong(); val = Convert.ChangeType(longVal, elementType); Globs.SetMember(f, this, val); break; } throw new NotImplementedException(""); } // ReSharper disable once CSharpWarnings::CS0162 // ReSharper disable once HeuristicUnreachableCode throw new NotImplementedException(""); case MarshalType.FixedLengthArray: case MarshalType.VariableLengthArray: var supportedElementaryTypes = new[] { typeof(byte[]), typeof(ushort[]), typeof(uint[]) }; if (supportedElementaryTypes.Contains(elementType)) { if (r.HasValue) { // ReSharper disable once AssignNullToNotNullAttribute val = r.ReadContentAs(elementType, null); Globs.SetMember(f, this, val); } else { // ReSharper disable once AssignNullToNotNullAttribute Object nullObj = Activator.CreateInstance(elementType, 0x0); Globs.SetMember(f, this, nullObj); skipCloseElement = true; } break; } // ReSharper disable once RedundantIfElseBlock else { throw new NotImplementedException(""); } case MarshalType.Union: // ReSharper disable once AssignNullToNotNullAttribute val = Activator.CreateInstance(Type.GetType(containingElementType)); ((TpmStructureBase)val).InternalReadXml(r); Globs.SetMember(f, this, val); break; default: throw new NotImplementedException(""); } if (!skipCloseElement) { r.ReadEndElement(); } skipCloseElement = false; } }
private void Init() { try { XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreComments = true; settings.IgnoreWhitespace = true; System.IO.MemoryStream stream = new System.IO.MemoryStream(serializedManifest); reader = XmlReader.Create(stream, settings); if (reader.Read() && reader.Name == "provider") { guid = new Guid(reader.GetAttribute("guid")); name = reader.GetAttribute("name"); fileName = reader.GetAttribute("resourceFileName"); } } catch (Exception e) { Debug.Assert(false, "Exception during manifest parsing"); name = ""; error = e; } inited = true; }
public override bool CanReadToken(XmlReader reader) { return (reader.IsStartElement(WSSecurity10Constants.Elements.BinarySecurityToken, WSSecurity10Constants.Namespace) && reader.GetAttribute(WSSecurity10Constants.Attributes.ValueType) == TokenTypes.SimpleWebToken); }
public override void gaxb_load(XmlReader reader, object _parent, Hashtable args) { base.gaxb_load(reader, _parent, args); if(reader == null && _parent == null) return; parent = _parent; if(this.GetType() == typeof( PUColorButton )) { gaxb_addToParent(); } xmlns = reader.GetAttribute("xmlns"); string attr; attr = reader.GetAttribute("onTouchUp"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { onTouchUp = attr; } attr = reader.GetAttribute("onTouchDown"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { onTouchDown = attr; } attr = reader.GetAttribute("pressedColor"); if(attr != null) { attr = PlanetUnityOverride.processString(_parent, attr); } if(attr != null) { pressedColor = new Color().PUParse(attr); } }
private void ParseCurve(XmlReader r) { if (!r.ReadToDescendant("curve")) { return; } do { if (r.IsEmptyElement) { continue; } string name = r.GetAttribute("name"); // this.reader["name"]; if (string.IsNullOrEmpty(name)) { continue; } var cur = new Curve(name); using (var rr = r.ReadSubtree()) { rr.Read(); while (rr.Read()) { switch (rr.NodeType) { case XmlNodeType.Element: if (rr.Name.Equals("point", StringComparison.Ordinal)) { string sx = rr.GetAttribute("x") ?? string.Empty; string sy = rr.GetAttribute("y") ?? string.Empty; try { cur.Add(XmlConvert.ToDouble(sx), XmlConvert.ToDouble(sy)); } catch (FormatException) { LogException(ErrorCode.Err202, rr.ReadInnerXml()); } } break; case XmlNodeType.Comment: cur.Comment = rr.Value; break; } } } try { net.Curves.Add(cur); } catch (ArgumentException) { LogException(ErrorCode.Err215, cur.Name); } } while(r.ReadToNextSibling("curve")); r.ReadEndElement(); }