public T Parse <T>(string body) where T : TopResponse { Type type = typeof(T); string rootTagName = GetRootElement(body); string key = type.FullName; if (Constants.ERROR_RESPONSE.Equals(rootTagName)) { key += ("_" + Constants.ERROR_RESPONSE); } XmlSerializer serializer = null; bool incl = false; rwLock.AcquireReaderLock(50); try { if (rwLock.IsReaderLockHeld) { incl = parsers.TryGetValue(key, out serializer); } } finally { if (rwLock.IsReaderLockHeld) { rwLock.ReleaseReaderLock(); } } if (!incl || serializer == null) { XmlAttributes rootAttrs = new XmlAttributes(); rootAttrs.XmlRoot = new XmlRootAttribute(rootTagName); XmlAttributeOverrides attrOvrs = new XmlAttributeOverrides(); attrOvrs.Add(type, rootAttrs); serializer = new XmlSerializer(type, attrOvrs); rwLock.AcquireWriterLock(50); try { if (rwLock.IsWriterLockHeld) { parsers[key] = serializer; } } finally { if (rwLock.IsWriterLockHeld) { rwLock.ReleaseWriterLock(); } } } object obj = null; using (System.IO.Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(body))) { obj = serializer.Deserialize(stream); } T rsp = (T)obj; if (rsp != null) { rsp.Body = body; } return(rsp); }
/// <summary> /// Loads and parses the given RICO file. /// </summary> /// <param name="packageName">Package name</param> /// <param name="ricoDefPath">Definition file path</param> /// <param name="isLocal">True if this is a local settings file, false for author settings file</param> /// <returns>Parsed Ploppable RICO definition file</returns> public static PloppableRICODefinition ParseRICODefinition(string packageName, string ricoDefPath, bool isLocal = false) { // Note here we're using insanityOK as a local settings flag. string localOrAuthor = isLocal ? "local" : "author"; try { // Open file. using (StreamReader reader = new StreamReader(ricoDefPath)) { // Create new XML (de)serializer XmlAttributes attrs = new XmlAttributes(); XmlElementAttribute attr = new XmlElementAttribute(); attr.ElementName = "RICOBuilding"; attr.Type = typeof(RICOBuilding); XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); attrOverrides.Add(typeof(RICOBuilding), "Building", attrs); // Read XML. var xmlSerializer = new XmlSerializer(typeof(PloppableRICODefinition), attrOverrides); var result = xmlSerializer.Deserialize(reader) as PloppableRICODefinition; StringBuilder errorList; if (result.Buildings.Count == 0) { Debugging.Message("no parseable buildings in " + localOrAuthor + " XML settings file"); } else { foreach (var building in result.Buildings) { // Check for fatal errors in each building. errorList = building.fatalErrors; if (errorList.Length == 0) { // No fatal errors; check for non-fatal errors. errorList = building.nonFatalErrors; if (errorList.Length != 0) { // Errors found - how we report them depends on whether its local or author settings (we're assuming mod settings are fine). if (isLocal && building.ricoEnabled) { // Errors in local settings need to be reported direct to user, except for buildings that aren't activated in RICO. Debugging.ErrorBuffer.Append(errorList.ToString()); Debugging.Message("non-fatal errors for building '" + building.name + "' in local settings"); } else if (ModSettings.debugLogging) { // Errors in other settings should be logged if verbose logging is enabled, but otherwise continue. errorList.Insert(0, "found the following non-fatal errors for building '" + building.name + "' in author settings:\r\n"); Debugging.Message(errorList.ToString()); } } } else { // Fatal errors! Need to be reported direct to user and the building ignored. Debugging.ErrorBuffer.Append(errorList.ToString()); Debugging.Message("fatal errors for building '" + building.name + "' in " + localOrAuthor + " settings"); } } } reader.Close(); return(result); } } catch (Exception e) { Debugging.ErrorBuffer.AppendLine(String.Format("Unexpected Exception while deserializing " + localOrAuthor + " RICO file {0} ({1} [{2}])", packageName, e.Message, e.InnerException != null ? e.InnerException.Message : "")); return(null); } }
/// <summary> /// Инициализация переопределенных тегов для класса In1 /// </summary> private static void GetElementAttributeIn1() { var myElementAttribute = new XmlElementAttribute("IN1.1") { Order = 0 }; var myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "Id", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.2", Order = 1 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "PlanId", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.3", Order = 2 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "CompanyId", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.4", Order = 3 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "CompanyName", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.5", Order = 4 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "AddressSmo", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.6", Order = 5 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "FioInSmo", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.7", Order = 6 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "Phone", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.12", Order = 7 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "DateBeginInsurence", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.13", Order = 8 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "DateEndInsurence", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.15", Order = 9 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "CodeOfRegion", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.16", Order = 10 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "FioList", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.18", Order = 11 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "BirthDay", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.19", Order = 12 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "AddressList", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.35", Order = 13 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "InsuranceType", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.36", Order = 14 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "InsuranceSerNum", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.42", Order = 15 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "Employment", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.43", Order = 16 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "Sex", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.49", Order = 17 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "IdentificatorsList", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.52", Order = 18 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(IN1), "PlaceOfBirth", myAttributes); }
public void Run() { DTO dto = new DTO { additionalInformation = "This information will be serialized separately", stamp = DateTime.UtcNow, name = "Marley", value = 72.34, index = 7 }; // this will allow us to omit the xmlns:xsi namespace var ns = new XmlSerializerNamespaces(); ns.Add( "", "" ); XmlSerializer s1 = new XmlSerializer(typeof(DTO)); var builder = new System.Text.StringBuilder(); var settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent= true }; Console.WriteLine("\nSerialize using the in-line (compile-time) attributes: "); using ( XmlWriter writer = XmlWriter.Create(builder, settings)) { s1.Serialize(writer, dto, ns); } Console.WriteLine("{0}",builder.ToString()); Console.WriteLine("\n"); // use a default namespace ns = new XmlSerializerNamespaces(); string myns = "urn:www.example.org"; ns.Add( "", myns ); XmlAttributeOverrides overrides = new XmlAttributeOverrides(); XmlAttributes attrs = new XmlAttributes(); // override the (implicit) XmlRoot attribute XmlRootAttribute attr1 = new XmlRootAttribute { Namespace = myns, ElementName = "DTO-Annotations", }; attrs.XmlRoot = attr1; overrides.Add(typeof(DTO), attrs); // "un-ignore" the first property // define an XmlElement attribute, for a type of "String", with no namespace var a2 = new XmlElementAttribute(typeof(String)) { ElementName="note", Namespace = myns }; // add that XmlElement attribute to the 2nd bunch of attributes attrs = new XmlAttributes(); attrs.XmlElements.Add(a2); attrs.XmlIgnore = false; // add that bunch of attributes to the container for the type, and // specifically apply that bunch to the "Label" property on the type. overrides.Add(typeof(DTO), "additionalInformation", attrs); // ignore the other properties // add the XmlIgnore attribute to the 2nd bunch of attributes attrs = new XmlAttributes(); attrs.XmlIgnore = true; // add that bunch of attributes to the container for the type, and // specifically apply that bunch to the "Label" property on the type. overrides.Add(typeof(DTO), "stamp", attrs); overrides.Add(typeof(DTO), "name", attrs); overrides.Add(typeof(DTO), "value", attrs); overrides.Add(typeof(DTO), "index", attrs); XmlSerializer s2 = new XmlSerializer(typeof(DTO), overrides); Console.WriteLine("\nSerialize using the override attributes: "); builder.Length = 0; using ( XmlWriter writer = XmlWriter.Create(builder, settings)) { s2.Serialize(writer, dto, ns); } Console.WriteLine("{0}",builder.ToString()); Console.WriteLine("\n"); }
/// <summary> /// Serializes the specified Class to XML. /// </summary> /// <param name="path">The path.</param> /// <param name="object">The @object.</param> /// <returns></returns> public static Boolean Serialize(String path, object @object) { try { File.Delete(path); } catch { } FileStream fs = null; try { using (fs = new FileStream(path, FileMode.Create)) { using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8)) { if (@object.GetType().ToString() == "Quester.Profile.QuesterProfile") { // create a XmlAttributes class with empty namespace and namespace disabled var xmlAttributes = new XmlAttributes { XmlType = new XmlTypeAttribute { Namespace = "" }, Xmlns = false }; // create a XmlAttributeOverrides class var xmlAttributeOverrides = new XmlAttributeOverrides(); // implement our previously created XmlAttributes to the overrider for our specificed class xmlAttributeOverrides.Add(@object.GetType(), xmlAttributes); // initialize the serializer for our class and attribute override var s = new System.Xml.Serialization.XmlSerializer(@object.GetType(), xmlAttributeOverrides); // create a blank XmlSerializerNamespaces var xmlSrzNamespace = new XmlSerializerNamespaces(); xmlSrzNamespace.Add("", ""); // Serialize with blank XmlSerializerNames using our initialized serializer with namespace disabled s.Serialize(w, @object, xmlSrzNamespace); // All kind of namespace are totally unable to serialize. } else { var s = new System.Xml.Serialization.XmlSerializer(@object.GetType()); s.Serialize(w, @object); } } } return(true); } catch (Exception ex) { try { if (fs != null) { fs.Close(); } } catch { } Logging.WriteError("Serialize(String path, object @object)#2: " + ex); MessageBox.Show("XML Serialize: " + ex); } return(false); }
public override string ToString () { string result = string.Empty; using (MemoryStream stream = new MemoryStream ()) { using (StreamReader sr = new StreamReader (stream)) { XmlTextWriter writer = null; try { writer = new XmlTextWriter (stream, System.Text.Encoding.UTF8); XmlAttributes attrs = new XmlAttributes (); XmlElementAttribute attr = new XmlElementAttribute (); attr.ElementName = "UnknownItemSerializer"; attr.Type = typeof (UnknownItemSerializer); attrs.XmlElements.Add (attr); XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides (); attrOverrides.Add (typeof (TestClass), "Item", attrs); XmlSerializer serializer = new XmlSerializer (this.GetType (), attrOverrides); serializer.Serialize (writer, this); stream.Position = 0; result = sr.ReadToEnd (); } finally { if (writer != null) writer.Close (); } } } return result; }
private bool CreateCSProject <T>(IEnumerable <T> objects, XMLConfig config) { bool success = true; Project doc = objects.ToList()[0] as Project; if (doc == null) { BH.Engine.Reflection.Compute.RecordError("The CSProject schema requires a full system to be provided as a single push operation."); return(false); } try { System.Reflection.PropertyInfo[] bhomProperties = typeof(BHoMObject).GetProperties(); XmlAttributeOverrides overrides = new XmlAttributeOverrides(); foreach (System.Reflection.PropertyInfo pi in bhomProperties) { overrides.Add(typeof(BHoMObject), pi.Name, new XmlAttributes { XmlIgnore = true }); } XmlSerializerNamespaces xns = new XmlSerializerNamespaces(); xns.Add("", ""); List <string> xmlParts = new List <string>(); xmlParts.Add("<Project ToolsVersion=\"" + doc.ToolsVersion + "\" DefaultTarget=\"" + doc.DefaultTargets + "\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">"); StringWriter textWriter = new StringWriter(); XmlSerializer szer = new XmlSerializer(typeof(BH.oM.XML.CSProject.Import), overrides); for (int x = 0; x < doc.Imports.Count - 1; x++) { szer.Serialize(textWriter, doc.Imports[x], xns); xmlParts.Add(textWriter.ToString()); textWriter = new StringWriter(); //To be safe } szer = new XmlSerializer(typeof(BH.oM.XML.CSProject.PropertyGroup), overrides); for (int x = 0; x < doc.PropertyGroups.Count - 1; x++) { szer.Serialize(textWriter, doc.PropertyGroups[x], xns); xmlParts.Add(textWriter.ToString()); textWriter = new StringWriter(); //To be safe } szer = new XmlSerializer(typeof(BH.oM.XML.CSProject.ItemGroup), overrides); foreach (var i in doc.ItemGroups) { szer.Serialize(textWriter, i, xns); xmlParts.Add(textWriter.ToString()); textWriter = new StringWriter(); } szer = new XmlSerializer(typeof(BH.oM.XML.CSProject.Import), overrides); szer.Serialize(textWriter, doc.Imports.Last(), xns); xmlParts.Add(textWriter.ToString()); textWriter = new StringWriter(); szer = new XmlSerializer(typeof(BH.oM.XML.CSProject.PropertyGroup), overrides); szer.Serialize(textWriter, doc.PropertyGroups.Last(), xns); xmlParts.Add(textWriter.ToString()); textWriter = new StringWriter(); xmlParts.Add("</Project>"); StreamWriter sw = new StreamWriter(_fileSettings.GetFullFileName()); xmlParts = xmlParts.Select(x => Regex.Replace(x, @"<\?xml version=""1.0"" encoding=""utf-[0-9]*""\?>\r\n", "")).ToList(); xmlParts = xmlParts.Select(x => x.Replace("q1:", "")).ToList(); sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); foreach (string s in xmlParts) { sw.WriteLine(s); } sw.Close(); } catch (Exception e) { BH.Engine.Reflection.Compute.RecordError(e.ToString()); success = false; } return(success); }
private static XmlAttributeOverrides GenerateMzIdentMlOverrides(string namespaceUrl) { // root override: affects only MzIdentMLType //[System.Xml.Serialization.XmlRootAttribute("MzIdentML", Namespace = "http://psidev.info/psi/pi/mzIdentML/1.1", IsNullable = false)] // all: //[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://psidev.info/psi/pi/mzIdentML/1.1")] var xmlOverrides = new XmlAttributeOverrides(); var xmlTypeNsOverride = new XmlAttributes(); var xmlTypeNs = new XmlTypeAttribute { Namespace = namespaceUrl }; xmlTypeNsOverride.XmlType = xmlTypeNs; var xmlRootOverrides = new XmlAttributes { XmlType = xmlTypeNs }; var xmlRootOverride = new XmlRootAttribute { ElementName = "MzIdentML", Namespace = namespaceUrl, IsNullable = false }; xmlRootOverrides.XmlRoot = xmlRootOverride; xmlOverrides.Add(typeof(MzIdentMLType), xmlRootOverrides); xmlOverrides.Add(typeof(cvType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SpectrumIdentificationItemRefType), xmlTypeNsOverride); xmlOverrides.Add(typeof(PeptideHypothesisType), xmlTypeNsOverride); xmlOverrides.Add(typeof(FragmentArrayType), xmlTypeNsOverride); xmlOverrides.Add(typeof(IonTypeType), xmlTypeNsOverride); xmlOverrides.Add(typeof(CVParamType), xmlTypeNsOverride); xmlOverrides.Add(typeof(UserParamType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ParamType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ParamListType), xmlTypeNsOverride); xmlOverrides.Add(typeof(PeptideEvidenceRefType), xmlTypeNsOverride); xmlOverrides.Add(typeof(AnalysisDataType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SpectrumIdentificationListType), xmlTypeNsOverride); xmlOverrides.Add(typeof(MeasureType), xmlTypeNsOverride); xmlOverrides.Add(typeof(IdentifiableType), xmlTypeNsOverride); xmlOverrides.Add(typeof(BibliographicReferenceType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ProteinDetectionHypothesisType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ProteinAmbiguityGroupType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ProteinDetectionListType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SpectrumIdentificationItemType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SpectrumIdentificationResultType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ExternalDataType), xmlTypeNsOverride); xmlOverrides.Add(typeof(FileFormatType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SpectraDataType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SpectrumIDFormatType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SourceFileType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SearchDatabaseType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ProteinDetectionProtocolType), xmlTypeNsOverride); xmlOverrides.Add(typeof(TranslationTableType), xmlTypeNsOverride); xmlOverrides.Add(typeof(MassTableType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ResidueType), xmlTypeNsOverride); xmlOverrides.Add(typeof(AmbiguousResidueType), xmlTypeNsOverride); xmlOverrides.Add(typeof(EnzymeType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SpectrumIdentificationProtocolType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SpecificityRulesType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SearchModificationType), xmlTypeNsOverride); xmlOverrides.Add(typeof(EnzymesType), xmlTypeNsOverride); xmlOverrides.Add(typeof(FilterType), xmlTypeNsOverride); xmlOverrides.Add(typeof(DatabaseTranslationType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ProtocolApplicationType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ProteinDetectionType), xmlTypeNsOverride); xmlOverrides.Add(typeof(InputSpectrumIdentificationsType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SpectrumIdentificationType), xmlTypeNsOverride); xmlOverrides.Add(typeof(InputSpectraType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SearchDatabaseRefType), xmlTypeNsOverride); xmlOverrides.Add(typeof(PeptideEvidenceType), xmlTypeNsOverride); xmlOverrides.Add(typeof(PeptideType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ModificationType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SubstitutionModificationType), xmlTypeNsOverride); xmlOverrides.Add(typeof(DBSequenceType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SampleType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ContactRoleType), xmlTypeNsOverride); xmlOverrides.Add(typeof(RoleType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SubSampleType), xmlTypeNsOverride); xmlOverrides.Add(typeof(AbstractContactType), xmlTypeNsOverride); xmlOverrides.Add(typeof(OrganizationType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ParentOrganizationType), xmlTypeNsOverride); xmlOverrides.Add(typeof(PersonType), xmlTypeNsOverride); xmlOverrides.Add(typeof(AffiliationType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ProviderType), xmlTypeNsOverride); xmlOverrides.Add(typeof(AnalysisSoftwareType), xmlTypeNsOverride); xmlOverrides.Add(typeof(InputsType), xmlTypeNsOverride); xmlOverrides.Add(typeof(DataCollectionType), xmlTypeNsOverride); xmlOverrides.Add(typeof(AnalysisProtocolCollectionType), xmlTypeNsOverride); xmlOverrides.Add(typeof(AnalysisCollectionType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SequenceCollectionType), xmlTypeNsOverride); return(xmlOverrides); }
/// <summary> /// Loops to the inheritance chain of an object, takes xml attributes from base /// objects and applies the overrides to the derived object /// </summary> /// <param name="baseType"></param> /// <param name="derivedType"></param> /// <param name="overrides"></param> public static void AddAttributeOverrides(Type baseType, Type derivedType, XmlAttributeOverrides overrides) { //loop, starting with derived type Type type = derivedType; do { //override attributes detected the next basetype type = type.BaseType; if (type == null) { break; } PropertyInfo[] props = baseType.GetProperties(); foreach (PropertyInfo pi in props) { //do not override attribute again if it already has override XmlAttributes overrideAttributes = overrides[derivedType, pi.Name]; if (overrideAttributes == null) { Object[] attributes = pi.GetCustomAttributes(true); foreach (Object a in attributes) { XmlAttributes attrs = new XmlAttributes(); if (a is XmlAttributeAttribute) { attrs.XmlAttribute = a as XmlAttributeAttribute; } else if (a is XmlElementAttribute) { attrs.XmlElements.Add(a as XmlElementAttribute); } else if (a is XmlIgnoreAttribute) { attrs.XmlIgnore = true; } else if (a is XmlArrayAttribute) { attrs.XmlArray = a as XmlArrayAttribute; } else if (a is XmlArrayItemAttribute) { attrs.XmlArrayItems.Add(a as XmlArrayItemAttribute); } else { continue; } bool exist = false; // first check if attribute does not exist // iterate over all properties because there can be property which hides type of the base class PropertyInfo[] properties = derivedType.GetProperties(); foreach (PropertyInfo pi2 in properties) { if (pi2.Name == pi.Name && pi2.Name != "Item") { Object[] attrs2 = derivedType.GetProperty(pi2.Name, pi2.PropertyType).GetCustomAttributes(false); foreach (Object a2 in attrs2) { if (a2.Equals(a)) { exist = true; } } } } if (!exist) // override { overrides.Add(derivedType, pi.Name, attrs); } } } } } while (!type.Equals(baseType)); }
private bool FillRecord(object rec, Tuple <long, XElement> pair) { long lineNo; XElement node; lineNo = pair.Item1; node = pair.Item2; fXElements = null; fieldValue = null; fieldConfig = null; pi = null; xpn = node.CreateNavigator(Configuration.NamespaceManager.NameTable); ToDictionary(node); foreach (KeyValuePair <string, ChoXmlRecordFieldConfiguration> kvp in Configuration.RecordFieldConfigurationsDict) { fieldValue = null; fieldConfig = kvp.Value; if (Configuration.PIDict != null) { Configuration.PIDict.TryGetValue(kvp.Key, out pi); } if (fieldConfig.XPath == "text()") { if (Configuration.GetNameWithNamespace(node.Name) == fieldConfig.FieldName) { object value = node; if (!RaiseBeforeRecordFieldLoad(rec, pair.Item1, kvp.Key, ref value)) { continue; } if (fieldConfig.ValueConverter != null) { value = fieldConfig.ValueConverter(value); } fieldValue = value is XElement ? node.Value : value; } else if (Configuration.ColumnCountStrict) { throw new ChoParserException("Missing '{0}' xml node.".FormatString(fieldConfig.FieldName)); } } else { if (/*!fieldConfig.UseCache && */ !xDict.ContainsKey(fieldConfig.FieldName)) { xNodes.Clear(); foreach (XPathNavigator z in xpn.Select(fieldConfig.XPath, Configuration.NamespaceManager)) { xNodes.Add(z.UnderlyingObject); } object value = xNodes; if (!RaiseBeforeRecordFieldLoad(rec, pair.Item1, kvp.Key, ref value)) { continue; } if (fieldConfig.ValueConverter != null) { fieldValue = fieldConfig.ValueConverter(value); } else { //object[] xNodes = ((IEnumerable)node.XPathEvaluate(fieldConfig.XPath, Configuration.NamespaceManager)).OfType<object>().ToArray(); //continue; XAttribute fXAttribute = xNodes.OfType <XAttribute>().FirstOrDefault(); if (fXAttribute != null) { fieldValue = fXAttribute.Value; } else { fXElements = xNodes.OfType <XElement>().ToArray(); if (fXElements != null) { if (Configuration.IsDynamicObject) { if (fieldConfig.IsArray != null && fieldConfig.IsArray.Value) { List <object> list = new List <object>(); foreach (var ele in fXElements) { if (fieldConfig.FieldType.IsSimple()) { list.Add(ChoConvert.ConvertTo(ele.Value, fieldConfig.FieldType.GetItemType())); } else { list.Add(ele.GetOuterXml().ToObjectFromXml(fieldConfig.FieldType.GetItemType())); } } fieldValue = list.ToArray(); } else { if (fieldConfig.FieldType == typeof(string) || fieldConfig.FieldType.IsSimple()) { XElement fXElement = fXElements.FirstOrDefault(); if (fXElement != null) { fieldValue = fXElement.Value; } } else { XmlAttributeOverrides overrides = null; var xattribs = new XmlAttributes(); var xroot = new XmlRootAttribute(fieldConfig.FieldName); xattribs.XmlRoot = xroot; overrides = new XmlAttributeOverrides(); overrides.Add(fieldConfig.FieldType, xattribs); XElement fXElement = fXElements.FirstOrDefault(); if (fXElement != null) { fieldValue = fXElement.GetOuterXml().ToObjectFromXml(fieldConfig.FieldType, overrides); } } } } else { XmlAttributeOverrides overrides = null; var xattribs = new XmlAttributes(); var xroot = new XmlRootAttribute(fieldConfig.FieldName); xattribs.XmlRoot = xroot; overrides = new XmlAttributeOverrides(); overrides.Add(fieldConfig.FieldType, xattribs); XElement fXElement = fXElements.FirstOrDefault(); if (fXElement != null) { fieldValue = fXElement.GetOuterXml().ToObjectFromXml(fieldConfig.FieldType, overrides); } } } else if (Configuration.ColumnCountStrict) { throw new ChoParserException("Missing '{0}' xml node.".FormatString(fieldConfig.FieldName)); } } } } else { if (xDict[fieldConfig.FieldName].Count == 1) { fieldValue = xDict[fieldConfig.FieldName][0]; } else { fieldValue = xDict[fieldConfig.FieldName]; } if (!RaiseBeforeRecordFieldLoad(rec, pair.Item1, kvp.Key, ref fieldValue)) { continue; } if (fieldConfig.ValueConverter != null) { fieldValue = fieldConfig.ValueConverter(fieldValue); } } } if (Configuration.IsDynamicObject) { if (kvp.Value.FieldType == null) { kvp.Value.FieldType = fieldValue is ICollection ? typeof(string[]) : DiscoverFieldType(fieldValue as string); } } else { if (pi != null) { kvp.Value.FieldType = pi.PropertyType; } else { kvp.Value.FieldType = typeof(string); } } if (fieldValue is string) { fieldValue = CleanFieldValue(fieldConfig, kvp.Value.FieldType, fieldValue as string); } try { bool ignoreFieldValue = fieldConfig.IgnoreFieldValue(fieldValue); if (ignoreFieldValue) { fieldValue = fieldConfig.IsDefaultValueSpecified ? fieldConfig.DefaultValue : null; } if (Configuration.IsDynamicObject) { var dict = rec as IDictionary <string, Object>; if (!fieldConfig.IsArray.CastTo <bool>()) { dict.ConvertNSetMemberValue(kvp.Key, kvp.Value, ref fieldValue, Configuration.Culture); } else { dict[kvp.Key] = fieldValue; } if ((Configuration.ObjectValidationMode & ChoObjectValidationMode.MemberLevel) == ChoObjectValidationMode.MemberLevel) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } } else { if (pi != null) { rec.ConvertNSetMemberValue(kvp.Key, kvp.Value, ref fieldValue, Configuration.Culture); } else { throw new ChoMissingRecordFieldException("Missing '{0}' property in {1} type.".FormatString(kvp.Key, ChoType.GetTypeName(rec))); } if ((Configuration.ObjectValidationMode & ChoObjectValidationMode.MemberLevel) == ChoObjectValidationMode.MemberLevel) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } } if (!RaiseAfterRecordFieldLoad(rec, pair.Item1, kvp.Key, fieldValue)) { return(false); } } catch (ChoParserException) { throw; } catch (ChoMissingRecordFieldException) { if (Configuration.ThrowAndStopOnMissingField) { throw; } } catch (Exception ex) { ChoETLFramework.HandleException(ex); if (fieldConfig.ErrorMode == ChoErrorMode.ThrowAndStop) { throw; } try { if (Configuration.IsDynamicObject) { var dict = rec as IDictionary <string, Object>; if (dict.SetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } else if (dict.SetDefaultValue(kvp.Key, kvp.Value, Configuration.Culture)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } else { throw new ChoReaderException($"Failed to parse '{fieldValue}' value for '{fieldConfig.FieldName}' field.", ex); } } else if (pi != null) { if (rec.SetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } else if (rec.SetDefaultValue(kvp.Key, kvp.Value, Configuration.Culture)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } else { throw new ChoReaderException($"Failed to parse '{fieldValue}' value for '{fieldConfig.FieldName}' field.", ex); } } else { throw new ChoReaderException($"Failed to parse '{fieldValue}' value for '{fieldConfig.FieldName}' field.", ex); } } catch (Exception innerEx) { if (ex == innerEx.InnerException) { if (fieldConfig.ErrorMode == ChoErrorMode.IgnoreAndContinue) { continue; } else { if (!RaiseRecordFieldLoadError(rec, pair.Item1, kvp.Key, fieldValue, ex)) { throw new ChoReaderException($"Failed to parse '{fieldValue}' value for '{fieldConfig.FieldName}' field.", ex); } } } else { throw new ChoReaderException("Failed to assign '{0}' fallback value to '{1}' field.".FormatString(fieldValue, fieldConfig.FieldName), innerEx); } } } } return(true); }
public void SerializeObject(string studentFilename, string bookFilename) { XmlSerializer mySerializer; TextWriter writer; // Create the XmlAttributeOverrides and XmlAttributes objects. XmlAttributeOverrides myXmlAttributeOverrides = new XmlAttributeOverrides(); XmlAttributes myXmlAttributes = new XmlAttributes(); /* Create an XmlAttributeAttribute set it to * the XmlAttribute property of the XmlAttributes object.*/ XmlAttributeAttribute myXmlAttributeAttribute = new XmlAttributeAttribute(); myXmlAttributeAttribute.AttributeName = "Name"; myXmlAttributes.XmlAttribute = myXmlAttributeAttribute; // Add to the XmlAttributeOverrides. Specify the member name. myXmlAttributeOverrides.Add(typeof(Student), "StudentName", myXmlAttributes); // Create the XmlSerializer. mySerializer = new XmlSerializer(typeof(Student), myXmlAttributeOverrides); writer = new StreamWriter(studentFilename); // Create an instance of the class that will be serialized. Student myStudent = new Student(); // Set the Name property, which will be generated as an XML attribute. myStudent.StudentName = "James"; myStudent.StudentNumber = 1; // Serialize the class, and close the TextWriter. mySerializer.Serialize(writer, myStudent); writer.Close(); // Create the XmlAttributeOverrides and XmlAttributes objects. XmlAttributeOverrides myXmlBookAttributeOverrides = new XmlAttributeOverrides(); XmlAttributes myXmlBookAttributes = new XmlAttributes(); /* Create an XmlAttributeAttribute set it to * the XmlAttribute property of the XmlAttributes object.*/ XmlAttributeAttribute myXmlBookAttributeAttribute = new XmlAttributeAttribute("Name"); myXmlBookAttributes.XmlAttribute = myXmlBookAttributeAttribute; // Add to the XmlAttributeOverrides. Specify the member name. myXmlBookAttributeOverrides.Add(typeof(Book), "BookName", myXmlBookAttributes); // Create the XmlSerializer. mySerializer = new XmlSerializer(typeof(Book), myXmlBookAttributeOverrides); writer = new StreamWriter(bookFilename); // Create an instance of the class that will be serialized. Book myBook = new Book(); // Set the Name property, which will be generated as an XML attribute. myBook.BookName = ".NET"; myBook.BookNumber = 10; // Serialize the class, and close the TextWriter. mySerializer.Serialize(writer, myBook); writer.Close(); }
static void TestWmts() { XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); XmlAttributes ddsAttrs = new XmlAttributes(); XmlElementAttribute layerAttr = new XmlElementAttribute { ElementName = "Layer", Type = typeof(LayerType) }; ddsAttrs.XmlElements.Add(layerAttr); attrOverrides.Add(typeof(ContentsBaseType), "DatasetDescriptionSummary", ddsAttrs); #region ServiceIdentification LanguageStringType[] titles = new LanguageStringType[] { new LanguageStringType() { Value = "Web Map Tile Service" } }; LanguageStringType[] abstracts = new LanguageStringType[] { new LanguageStringType() { Value = "Service that contrains the map access interface to some TileMatrixSets" } }; LanguageStringType[] keyword1 = new LanguageStringType[] { new LanguageStringType() { Value = "tile" } }; KeywordsType keywordsType1 = new KeywordsType() { Keyword = keyword1 }; LanguageStringType[] keyword2 = new LanguageStringType[] { new LanguageStringType() { Value = "map" } }; KeywordsType keywordsType2 = new KeywordsType() { Keyword = keyword2 }; KeywordsType[] keywords = new KeywordsType[] { keywordsType1, keywordsType2 }; CodeType serviceType = new CodeType() { Value = "OGC WMTS" }; string[] serviceTypeVersion = new string[] { "1.0.0" }; string fees = "none"; string[] accessConstraints = new string[] { "none" }; ServiceIdentification serviceIdentification = new ServiceIdentification() { Title = titles, Abstract = abstracts, Keywords = keywords, ServiceType = serviceType, ServiceTypeVersion = serviceTypeVersion, Fees = fees, AccessConstraints = accessConstraints }; #endregion string href = "http://123"; #region ServiceProvider string poroviderName = "SharpMapServer"; OnlineResourceType providerSiteType = new OnlineResourceType() { href = href }; string[] voices = new string[] { "0000-00000000" }; string[] facsimiles = new string[] { "0001-00000001" }; TelephoneType phone = new TelephoneType() { Voice = voices, Facsimile = facsimiles }; string[] deliveryPoints = new string[] { "jinjiang" }; string city = "chengdu"; string administrativeArea = "sichuan"; string country = "china"; string[] electronicMailAddress = new string[] { "*****@*****.**" }; string postalCode = "123456"; AddressType address = new AddressType() { DeliveryPoint = deliveryPoints, City = city, AdministrativeArea = administrativeArea, Country = country, ElectronicMailAddress = electronicMailAddress, PostalCode = postalCode }; ContactType contactInfo = new ContactType() { Phone = phone, Address = address }; string individualName = "lc"; string positionName = "Senior Software Engineer"; ResponsiblePartySubsetType serviceContact = new ResponsiblePartySubsetType() { IndividualName = individualName, PositionName = positionName, ContactInfo = contactInfo }; ServiceProvider serviceProvider = new ServiceProvider() { ProviderName = poroviderName, ProviderSite = providerSiteType, ServiceContact = serviceContact }; #endregion #region OperationsMetadata Operation getCapabilitiesOperation = CapabilitiesHelper.GetOperation(href, "GetCapabilities"); Operation getTileOperation = CapabilitiesHelper.GetOperation(href, "GetTile"); Operation getFeatureinfoOperation = CapabilitiesHelper.GetOperation(href, "GetFeatureinfo"); Operation[] operations = new Operation[] { getCapabilitiesOperation, getTileOperation, getFeatureinfoOperation }; OperationsMetadata operationsMetadata = new OperationsMetadata() { Operation = operations }; #endregion Capabilities capabilities = new Capabilities() { ServiceIdentification = serviceIdentification, ServiceProvider = serviceProvider, OperationsMetadata = operationsMetadata }; IWmtsService wmts1Service = OgcServiceHelper.GetOgcService("WMTS", "1.0.0") as IWmtsService; wmts1Service.AddContent(capabilities, @"E:\LC\数据\双流\2014年遥感影像.img"); List <object> objs = new List <object>(); capabilities.Themes = new Themes[] { new Themes() { Theme = new Theme[] { new Theme() { Identifier = new CodeType() { Value = "123" } } } } }; objs.Add(capabilities); StringBuilder sb = new StringBuilder(); using (TextWriter tw = new StringWriter(sb)) { foreach (var item in objs) { if (item == null) { continue; } var serializer = new XmlSerializer(item.GetType(), attrOverrides); serializer.Serialize(tw, item); var val = sb.ToString(); File.WriteAllText("123.xml", val); sb.Clear(); } } }
//static XmlSerializerNamespaces _xmlSerializerNamespaces; static TemplatePackageManifest() { var v10Overrides = new XmlAttributeOverrides(); var v10DependencyEnumMap = new Dictionary <string, string>() { { "NoDependency", "NoDependency" }, { "PrimaryCmpFile", "BaseCmpFile" }, { "SharedCmpFile", "PointedToCmpFile" }, { "InsertedTemplate", "TemplateInsert" }, { "InsertedClause", "ClauseInsert" }, { "InsertedClauseLibrary", "ClauseLibraryInsert" }, { "InsertedImage", "ImageInsert" }, { "InterviewImage", "InterviewImage" }, { "VariableInsertedTemplate", "VariableTemplateInsert" }, { "VariableInsertedImage", "VariableImageInsert" }, { "MissingVariable", "MissingVariable" }, { "MissingFile", "MissingFile" }, { "AssembledTemplate", "Assemble" }, { "PublisherMapFile", "PublisherMapFile" }, { "UserMapFile", "UserMapFile" } }; foreach (var kv in v10DependencyEnumMap) { v10Overrides.Add(typeof(DependencyType), kv.Value, new XmlAttributes() { XmlEnum = new XmlEnumAttribute(kv.Key) }); } v10Overrides.Add(typeof(Dependency), "FileName", new XmlAttributes() { XmlAttribute = new XmlAttributeAttribute("target") }); v10Overrides.Add(typeof(TemplateInfo), "FileName", new XmlAttributes() { XmlAttribute = new XmlAttributeAttribute("name") }); var attributes = new XmlAttributes() { XmlArray = new XmlArrayAttribute("serverFiles") }; attributes.XmlArrayItems.Add(new XmlArrayItemAttribute("file")); v10Overrides.Add(typeof(TemplateInfo), "GeneratedHDFiles", attributes); _xmlSerializer = new XmlSerializer(typeof(TemplatePackageManifest), PackageNamespace); _xmlSerializer10 = new XmlSerializer(typeof(TemplatePackageManifest), v10Overrides, null, null, PackageNamespace10); //_xmlSerializerNamespaces = new XmlSerializerNamespaces(); //_xmlSerializerNamespaces.Add(string.Empty, string.Empty); /* * TemplatePackageManifest manifest = new TemplatePackageManifest(); * var main = manifest.MainTemplate = new TemplateInfo(); * main.FileName = "myfilename.rtf"; * main.EffectiveComponentFile = "mycomponentfile.cmp"; * string xml; * using (var sw = new StringWriter()) * { * _xmlSerializer10.Serialize(sw, manifest); * xml = sw.ToString(); * } */ }
public XmlDumper(bool ignoreSensitive, R2RReader r2r, TextWriter writer, bool raw, bool header, bool disasm, IntPtr disassembler, bool unwind, bool gc, bool sectionContents) { _ignoreSensitive = ignoreSensitive; _r2r = r2r; _writer = writer; XmlDocument = new XmlDocument(); _raw = raw; _header = header; _disasm = disasm; _disassembler = disassembler; _unwind = unwind; _gc = gc; _sectionContents = sectionContents; _ignoredProperties = new XmlAttributeOverrides(); XmlAttributes attrs = new XmlAttributes(); attrs.XmlIgnore = _ignoreSensitive; _ignoredProperties.Add(typeof(R2RHeader), "RelativeVirtualAddress", attrs); _ignoredProperties.Add(typeof(R2RHeader), "Size", attrs); _ignoredProperties.Add(typeof(R2RImportSection), "SectionRVA", attrs); _ignoredProperties.Add(typeof(R2RImportSection), "SectionSize", attrs); _ignoredProperties.Add(typeof(R2RImportSection), "EntrySize", attrs); _ignoredProperties.Add(typeof(R2RImportSection), "SignatureRVA", attrs); _ignoredProperties.Add(typeof(R2RImportSection), "AuxiliaryDataRVA", attrs); _ignoredProperties.Add(typeof(R2RImportSection.ImportSectionEntry), "SignatureSample", attrs); _ignoredProperties.Add(typeof(R2RImportSection.ImportSectionEntry), "SignatureRVA", attrs); _ignoredProperties.Add(typeof(RuntimeFunction), "StartAddress", attrs); _ignoredProperties.Add(typeof(RuntimeFunction), "UnwindRVA", attrs); _ignoredProperties.Add(typeof(R2RSection), "RelativeVirtualAddress", attrs); _ignoredProperties.Add(typeof(R2RSection), "Size", attrs); }
public static ShaderWindowSettings LoadConfiguration(out DialogResult result) { if (!File.Exists(ShaderManager.DefaultConfigurationFile)) { result = DialogResult.OK; return(new ShaderWindowSettings()); } var olderVersion = false; using (var reader = XmlReader.Create(ShaderManager.DefaultConfigurationFile)) { olderVersion = reader.ReadToDescendant("ShaderConfiguration") && reader.AttributeCount == 0; } if (olderVersion) { result = MessageBox.Show( Resources.ConfigurationFileUpgrade_Message, Resources.ConfigurationFileUpgrade_Caption, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); if (result == DialogResult.Cancel) { return(null); } var overrides = new XmlAttributeOverrides(); var shaderAttributes = new XmlAttributes(); var materialElement = new XmlArrayItemAttribute(); materialElement.ElementName = "ShaderConfiguration"; materialElement.Type = typeof(MaterialConfiguration); shaderAttributes.XmlArrayItems.Add(materialElement); overrides.Add(typeof(ShaderWindowSettings), "Shaders", shaderAttributes); var bufferBindingAttributes = new XmlAttributes(); var textureBindingElement = new XmlArrayItemAttribute(); textureBindingElement.ElementName = "TextureBindingConfiguration"; textureBindingElement.Type = typeof(TextureBindingConfiguration); bufferBindingAttributes.XmlArray = new XmlArrayAttribute("TextureBindings"); bufferBindingAttributes.XmlArrayItems.Add(textureBindingElement); overrides.Add(typeof(ShaderConfiguration), "BufferBindings", bufferBindingAttributes); ShaderWindowSettings configuration; var serializer = new XmlSerializer(typeof(ShaderWindowSettings), overrides); using (var reader = XmlReader.Create(ShaderManager.DefaultConfigurationFile)) { configuration = (ShaderWindowSettings)serializer.Deserialize(reader); } if (result == DialogResult.Yes) { ShaderManager.SaveConfiguration(configuration); } else { return(configuration); } } result = DialogResult.OK; try { return(ShaderManager.LoadConfiguration()); } catch { result = DialogResult.Cancel; throw; } }
private bool CreateGBXML <T>(IEnumerable <T> objects, XMLConfig config) { bool success = true; if (config.Settings == null) { BH.Engine.Reflection.Compute.RecordError("Please provide a suitable set of GBXMLSettings with the XMLConfig to determine how the GBXML file should be created"); return(false); } GBXMLSettings settings = config.Settings as GBXMLSettings; if (settings == null) { BH.Engine.Reflection.Compute.RecordError("Please provide a suitable set of GBXMLSettings with the XMLConfig to determine how the GBXML file should be created"); return(false); } GBXMLDocumentBuilder doc = objects.ToList()[0] as GBXMLDocumentBuilder; if (doc == null) { BH.Engine.Reflection.Compute.RecordError("The GBXML schema requires a full model to be provided as a single push operation. For pushing to the GBXML version, you need to plug your objects into a GBXMLDocumentBuilder which collates the objects for pushing and push that to GBXML via this adapter."); return(false); } List <IBHoMObject> bhomObjects = new List <IBHoMObject>(); bhomObjects.AddRange(doc.Buildings); bhomObjects.AddRange(doc.Levels); bhomObjects.AddRange(doc.ShadingElements); bhomObjects.AddRange(doc.UnassignedPanels); if (settings.ExportDetail == oM.Adapters.XML.Enums.ExportDetail.Full) { foreach (List <Panel> p in doc.ElementsAsSpaces) { bhomObjects.AddRange(p); } } else if (settings.ExportDetail == oM.Adapters.XML.Enums.ExportDetail.BuildingShell) { bhomObjects.AddRange(doc.ElementsAsSpaces.ExternalElements()); } else { BH.Engine.Reflection.Compute.RecordError("The ExportDetail has not been appropriately set. Please set the ExportDetail to continue"); return(false); } GBXML gbx = bhomObjects.ToGBXML(settings); try { System.Reflection.PropertyInfo[] bhomProperties = typeof(BHoMObject).GetProperties(); XmlAttributeOverrides overrides = new XmlAttributeOverrides(); foreach (System.Reflection.PropertyInfo pi in bhomProperties) { overrides.Add(typeof(BHoMObject), pi.Name, new XmlAttributes { XmlIgnore = true }); } XmlSerializerNamespaces xns = new XmlSerializerNamespaces(); XmlSerializer szer = new XmlSerializer(typeof(BH.Adapter.XML.GBXMLSchema.GBXML), overrides); TextWriter ms = new StreamWriter(_fileSettings.GetFullFileName()); szer.Serialize(ms, gbx, xns); ms.Close(); } catch (Exception e) { BH.Engine.Reflection.Compute.RecordError(e.ToString()); success = false; } return(success); }
public static void Add <T>(this XmlAttributeOverrides overrides, XmlAttributes attributes) { overrides.Add(typeof(T), attributes); }
public static void SerializeReport(string folderPath, IEnumerable <ConfigModel> models) { if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } var filename = Path.Combine(folderPath, "report.xml"); try { var writerSettings = new XmlWriterSettings { Encoding = new UTF8Encoding(false), Indent = true, IndentChars = " " }; //We only include services with errors, new operations or operations requiring a configuration update var configModelsToOutput = models.Where(configModel => configModel.AnalysisErrors.Any() || configModel.ServiceOperationsList.Where(op => op.IsAutoConfiguring || op.AnalysisErrors.Any()).Any()) .ToArray(); var doc = new XDocument(); using (var writer = doc.CreateWriter()) { writer.WriteStartElement("Overrides"); writer.WriteAttributeString("xmlns", "xsd", null, "http://www.w3.org/2001/XMLSchema"); writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance"); writer.WriteAttributeString("xsi", "noNamespaceSchemaLocation", null, "https://raw.githubusercontent.com/aws/aws-tools-for-powershell/master/XmlSchemas/ConfigurationOverrides/overrides.xsd"); foreach (var configModel in configModelsToOutput) { var overrides = new XmlAttributeOverrides(); overrides.Add(typeof(ConfigModel), new XmlAttributes() { XmlRoot = new XmlRootAttribute("Service") }); var serializer = new XmlSerializer(typeof(ConfigModel), overrides); serializer.Serialize(writer, configModel); } writer.WriteEndElement(); //Overrides } foreach (var configModel in doc.Root.Elements().Zip(configModelsToOutput, (element, model) => (element, model))) { foreach (var error in configModel.model.AnalysisErrors) { configModel.element.AddFirst(new XComment($"ERROR - {error.Message}")); } var serviceOperationsElement = configModel.element.Element("ServiceOperations"); var operations = serviceOperationsElement.Elements() .Join(configModel.model.ServiceOperationsList, element => element.Attribute("MethodName").Value, operation => operation.MethodName, (element, operation) => (element, operation)) .ToArray(); foreach (var operation in operations) { //We only include in the report new operations (IsAutoConfiguring=true) and operations requiring configuration updated if (operation.operation.IsAutoConfiguring || operation.operation.AnalysisErrors.Any()) { var firstOperationChildElement = operation.element.Elements().FirstOrDefault(); if (operation.operation.IsAutoConfiguring) { operation.element.AddFirst(new XComment($"INFO - This is a new cmdlet.")); } foreach (var error in operation.operation.AnalysisErrors) { operation.element.AddFirst(new XComment($"ERROR - {error.Message}")); } try { //Excluded operations have Analyzer == null if (operation.operation.Analyzer != null) { if (operation.operation.Analyzer.AnalyzedParameters.Any()) { var parametersComments = operation.operation.Analyzer.AnalyzedParameters.Select(PropertyChangedEventArgs => GetParameterCommentForReport(PropertyChangedEventArgs, operation.operation.Analyzer)); operation.element.Add(new XComment($"INFO - Parameters:\n {string.Join(";\n ", parametersComments)}.")); } var returnTypeComment = GetReturnTypeComment(operation.operation.Analyzer); if (returnTypeComment != null) { operation.element.Add(new XComment($"INFO - {returnTypeComment}")); } } } catch (Exception e) { operation.element.AddFirst(new XComment($"ERROR - Exception while generating operation report: {e.ToString()}")); } } else { operation.element.Remove(); } } } doc.Save(filename); } catch (Exception e) { throw new IOException("Unable to serialize report to " + filename, e); } }
public static void Add <T>(this XmlAttributeOverrides overrides, Expression <Func <T, object> > propertySelector, XmlAttributes attributes) { overrides.Add(typeof(T), propertySelector.GetPropertyName(), attributes); }
/// <summary> /// Requests CAS ticket validation by the configured CAS server. /// </summary> /// <param name="validationUrl">the URL to use for ticket validation</param> /// <param name="ticket"> /// the ticket returned by the CAS server from a successful authentication /// </param> /// <returns> /// the XML response representing the ticket validation /// </returns> protected override string RetrieveResponseFromServer(string validationUrl, string ticket) { // Create the SAML Request and populate its values. Schema.Saml11.Protocol.Request.RequestType samlRequest = new Schema.Saml11.Protocol.Request.RequestType { MajorVersion = "1", MinorVersion = "1", RequestId = Guid.NewGuid().ToString(), IssueInstant = DateTime.UtcNow, ItemsElementName = new[] { Schema.Saml11.Protocol.Request.RequestType.ItemsElementNames.AssertionArtifact }, Items = new object[] { ticket } }; // Create the XML representation of the SAML Request. StringBuilder samlRequestXml = new StringBuilder(); using (XmlWriter xmlWriter = XmlWriter.Create(samlRequestXml)) { // Need to add some overrides because of conflicting element names during serialization. var xmlOverrides = new XmlAttributeOverrides(); xmlOverrides.Add(typeof(Schema.XmlDsig.PgpDataType.ItemsElementNames), new XmlAttributes { XmlType = new XmlTypeAttribute("ItemsElementNamesOfPgpDataType") }); xmlOverrides.Add(typeof(Schema.XmlDsig.KeyInfoType.ItemsElementNames), new XmlAttributes { XmlType = new XmlTypeAttribute("ItemsElementNamesOfKeyInfoType") }); XmlSerializer xmlSerializer = new XmlSerializer(typeof(Schema.Saml11.Protocol.Request.RequestType), xmlOverrides); XmlSerializerNamespaces samlRequestNamespaces = new XmlSerializerNamespaces(); samlRequestNamespaces.Add("samlp", "urn:oasis:names:tc:SAML:1.0:protocol"); xmlSerializer.Serialize(xmlWriter, samlRequest, samlRequestNamespaces); } // Create the SOAP Envelope XML that will wrap around the SAML Request XML. Schema.SoapEnvelope.Envelope soapEnvelope = new Schema.SoapEnvelope.Envelope(); soapEnvelope.Header = new Schema.SoapEnvelope.Header(); soapEnvelope.Body = new Schema.SoapEnvelope.Body(); using (XmlReader xmlReader = XmlReader.Create(new StringReader(samlRequestXml.ToString()))) { XmlDocument doc = new XmlDocument(); doc.Load(xmlReader); XmlElement el = doc.DocumentElement; soapEnvelope.Body.Any = new[] { el }; } StringBuilder samlRequestStringBuilder = new StringBuilder(); XmlWriterSettings xmlWriterSettings = new XmlWriterSettings(); xmlWriterSettings.OmitXmlDeclaration = true; xmlWriterSettings.Indent = true; using (XmlWriter xmlWriter = XmlWriter.Create(samlRequestStringBuilder, xmlWriterSettings)) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(Schema.SoapEnvelope.Envelope)); XmlSerializerNamespaces soapEnvelopeNamespaces = new XmlSerializerNamespaces(); soapEnvelopeNamespaces.Add("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/"); xmlSerializer.Serialize(xmlWriter, soapEnvelope, soapEnvelopeNamespaces); } // Get the string representation of the SAML Request XML. string message = samlRequestStringBuilder.ToString(); protoLogger.Debug("Constructed SAML request:{0}{1}", Environment.NewLine, message); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(validationUrl); req.Method = "POST"; req.ContentType = "text/xml"; req.ContentLength = Encoding.UTF8.GetByteCount(message); req.CookieContainer = new CookieContainer(); req.Headers.Add("SOAPAction", "http://www.oasis-open.org/committees/security"); req.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); protoLogger.Debug("Request URI: " + req.RequestUri); protoLogger.Debug("Request headers: " + req.Headers); byte[] payload = Encoding.UTF8.GetBytes(message); using (Stream requestStream = req.GetRequestStream()) { requestStream.Write(payload, 0, payload.Length); } HttpWebResponse response = (HttpWebResponse)req.GetResponse(); Stream responseStream = response.GetResponseStream(); if (responseStream != null) { using (StreamReader responseReader = new StreamReader(responseStream)) { return(responseReader.ReadToEnd()); } } else { throw new ApplicationException("Unable to retrieve response stream."); } }
public static void Ignore <T>(this XmlAttributeOverrides overrides, Expression <Func <T, object> > propertySelector) { overrides.Add(typeof(T), propertySelector.GetPropertyName(), _ignore); }
/// <summary> /// Loads and parses the given RICO file. /// </summary> /// <param name="ricoDefPath">Definition file path</param> /// <param name="isLocal">True if this is a local settings file, false for author settings file</param> /// <returns>Parsed Ploppable RICO definition file</returns> public static PloppableRICODefinition ParseRICODefinition(string ricoDefPath, bool isLocal = false) { // Local settings flag. string localOrAuthor = isLocal ? "local" : "author"; try { // Open file. using (StreamReader reader = new StreamReader(ricoDefPath)) { // Create new XML (de)serializer XmlAttributes attrs = new XmlAttributes(); XmlElementAttribute attr = new XmlElementAttribute { ElementName = "RICOBuilding", Type = typeof(RICOBuilding) }; XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); attrOverrides.Add(typeof(RICOBuilding), "Building", attrs); // Read XML. XmlSerializer xmlSerializer = new XmlSerializer(typeof(PloppableRICODefinition), attrOverrides); PloppableRICODefinition result = xmlSerializer.Deserialize(reader) as PloppableRICODefinition; StringBuilder errorList; if (result.Buildings.Count == 0) { Logging.Message("no parseable buildings in ", localOrAuthor, " XML settings file at ", ricoDefPath); } else { foreach (RICOBuilding building in result.Buildings) { // Check for fatal errors in each building. errorList = building.FatalErrors; if (errorList.Length == 0) { // No fatal errors; check for non-fatal errors. errorList = building.NonFatalErrors; if (errorList.Length != 0) { if (isLocal && building.ricoEnabled) { // Errors in local settings need to be reported, except for buildings that aren't activated in RICO (e.g. for when the user has de-activated a RICO builidng with issues). Logging.Error("non-fatal errors for building '", building.Name, "' in local settings:\r\n", errorList); } else { // Errors in other settings should be logged if verbose logging is enabled, but otherwise continue. Logging.Message("non-fatal errors for building '", building.Name, "' in author settings:\r\n", errorList); } } } else { // Fatal errors! Need to be reported direct to user and the building ignored. Logging.Error("fatal errors for building '", building.Name, "' in ", localOrAuthor, " settings:\r\n", errorList); } } } reader.Close(); return(result); } } catch (Exception e) { Logging.LogException(e, "Unexpected Exception while deserializing ", localOrAuthor, " RICO file at ", ricoDefPath); return(null); } }
/// <summary> /// 序列化类到xml文档 /// </summary> /// <typeparam name="T">类</typeparam> /// <param name="para">类的对象</param> /// <param name="filePath">xml文档路径(包含文件名)</param> /// <returns>成功:true,失败:false</returns> public static bool XMLWriteToFile(List <FigureBaseModel> figures, string filePath, Type[] types = null) { try { XmlWriter writer = null; //声明一个xml编写器 XmlWriterSettings writerSetting = new XmlWriterSettings { Indent = true, //定义xml格式,自动创建新的行 Encoding = UTF8Encoding.UTF8, //编码格式 }; writer = XmlWriter.Create(filePath, writerSetting); XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); XmlAttributes attrs = new XmlAttributes(); XmlElementAttribute attrArc = new XmlElementAttribute(); attrArc.ElementName = "Arc"; attrArc.Type = typeof(ArcModel); XmlElementAttribute attrCircle = new XmlElementAttribute(); attrCircle.ElementName = "Circle"; attrCircle.Type = typeof(CircleModel); XmlElementAttribute attrEllipse = new XmlElementAttribute(); attrEllipse.ElementName = "Ellipse"; attrEllipse.Type = typeof(EllipseModel); XmlElementAttribute attrLwPolyline = new XmlElementAttribute(); attrLwPolyline.ElementName = "LwPolyline"; attrLwPolyline.Type = typeof(LwPolylineModel); XmlElementAttribute attrPoint = new XmlElementAttribute(); attrPoint.ElementName = "Point"; attrPoint.Type = typeof(PointModel); XmlElementAttribute attrPolyBezier = new XmlElementAttribute(); attrPolyBezier.ElementName = "PolyBezier"; attrPolyBezier.Type = typeof(PolyBezierModel); // Add the XmlElementAttribute to the collection of objects. attrs.XmlElements.Add(attrArc); attrs.XmlElements.Add(attrCircle); attrs.XmlElements.Add(attrEllipse); attrs.XmlElements.Add(attrLwPolyline); attrs.XmlElements.Add(attrPoint); attrs.XmlElements.Add(attrPolyBezier); attrOverrides.Add(typeof(Entities), "Figures", attrs); WXFDocument fgs = new WXFDocument() { Entities = new Entities() { Figures = figures } }; XmlSerializer xser = new XmlSerializer(typeof(WXFDocument), attrOverrides); //实例化序列化对象 xser.Serialize(writer, fgs); //序列化对象到xml文档 writer.Close(); } catch (Exception ex) { LogUtil.Instance.Error(ex.Message); return(false); } return(true); }
public T Parse(string body, Type type) { string key = type.FullName; XmlSerializer serializer = null; bool incl = false; rwLock.AcquireReaderLock(50); try { if (rwLock.IsReaderLockHeld) { incl = parsers.TryGetValue(key, out serializer); } } finally { if (rwLock.IsReaderLockHeld) { rwLock.ReleaseReaderLock(); } } if (!incl || serializer == null) { XmlAttributes rootAttrs = new XmlAttributes(); rootAttrs.XmlRoot = new XmlRootAttribute(Constants.QM_ROOT_TAG_RSP); XmlAttributeOverrides attrOvrs = new XmlAttributeOverrides(); attrOvrs.Add(type, rootAttrs); serializer = new XmlSerializer(type, attrOvrs); rwLock.AcquireWriterLock(50); try { if (rwLock.IsWriterLockHeld) { parsers[key] = serializer; } } finally { if (rwLock.IsWriterLockHeld) { rwLock.ReleaseWriterLock(); } } } object obj = null; using (System.IO.Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(body))) { obj = serializer.Deserialize(stream); } T rsp = (T)obj; if (rsp != null) { rsp.Body = body; } return(rsp); }
private bool CreateDefault <T>(IEnumerable <T> objects, XMLConfig config) { bool success = true; try { System.Reflection.PropertyInfo[] bhomProperties = typeof(BHoMObject).GetProperties(); XmlAttributeOverrides overrides = new XmlAttributeOverrides(); foreach (System.Reflection.PropertyInfo pi in bhomProperties) { overrides.Add(typeof(BHoMObject), pi.Name, new XmlAttributes { XmlIgnore = true }); } StringWriter stringWriter = new StringWriter(); XmlSerializerNamespaces xns = new XmlSerializerNamespaces(); xns.Add("", ""); XmlSerializer szer = new XmlSerializer(typeof(T), overrides); StreamWriter sw = new StreamWriter(_fileSettings.GetFullFileName()); List <T> obj = objects.ToList(); for (int x = 0; x < obj.Count; x++) { szer.Serialize(stringWriter, obj[x], xns); string line = stringWriter.ToString(); if (x > 0) { line = line.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n", ""); //Don't need this header on every item } sw.WriteLine(line); StringBuilder sb = stringWriter.GetStringBuilder(); sb.Remove(0, sb.Length); } sw.Close(); } catch (Exception e) { //Try exporting the objects manually if automatic serialisation didn't work try { List <string> xmlStrings = objects.Select(x => (x as object).ToXML()).ToList(); string xml = "<BHoM>"; xmlStrings.ForEach(x => xml += x); xml += "</BHoM>"; XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(xml); xdoc.Save(_fileSettings.GetFullFileName()); } catch (Exception ex) { //Well something went terribly wrong so lets give the user both error messages to help with debugging BH.Engine.Reflection.Compute.RecordError("An error occurred in serialising the objects of type " + objects.GetType() + ". Error messages will follow."); BH.Engine.Reflection.Compute.RecordError(e.ToString()); BH.Engine.Reflection.Compute.RecordError(ex.ToString()); success = false; } } return(success); }
public void SameItemType() { XmlArrayItemAttribute array1 = new XmlArrayItemAttribute("myname", typeof(SerializeMe)); XmlArrayItemAttribute array2 = new XmlArrayItemAttribute("myname", typeof(SerializeMe)); atts1.XmlArrayItems.Add(array1); atts2.XmlArrayItems.Add(array2); ov1.Add(typeof(SerializeMe), atts1); ov2.Add(typeof(SerializeMe), atts2); ThumbprintHelpers.SameThumbprint(ov1, ov2); }
internal static void LoadXmlFormatExtensions(Type[] extensionTypes, XmlAttributeOverrides overrides, XmlSerializerNamespaces namespaces) { Hashtable table = new Hashtable(); table.Add(typeof(ServiceDescription), new XmlAttributes()); table.Add(typeof(Import), new XmlAttributes()); table.Add(typeof(Port), new XmlAttributes()); table.Add(typeof(Service), new XmlAttributes()); table.Add(typeof(FaultBinding), new XmlAttributes()); table.Add(typeof(InputBinding), new XmlAttributes()); table.Add(typeof(OutputBinding), new XmlAttributes()); table.Add(typeof(OperationBinding), new XmlAttributes()); table.Add(typeof(Binding), new XmlAttributes()); table.Add(typeof(OperationFault), new XmlAttributes()); table.Add(typeof(OperationInput), new XmlAttributes()); table.Add(typeof(OperationOutput), new XmlAttributes()); table.Add(typeof(Operation), new XmlAttributes()); table.Add(typeof(PortType), new XmlAttributes()); table.Add(typeof(Message), new XmlAttributes()); table.Add(typeof(MessagePart), new XmlAttributes()); table.Add(typeof(Types), new XmlAttributes()); Hashtable extensions = new Hashtable(); foreach (Type extensionType in extensionTypes) { if (extensions[extensionType] != null) { continue; } extensions.Add(extensionType, extensionType); object[] attrs = extensionType.GetCustomAttributes(typeof(XmlFormatExtensionAttribute), false); if (attrs.Length == 0) { throw new ArgumentException(SR.Format(SR.RequiredXmlFormatExtensionAttributeIsMissing1, extensionType.FullName), nameof(extensionTypes)); } XmlFormatExtensionAttribute extensionAttr = (XmlFormatExtensionAttribute)attrs[0]; foreach (Type extensionPointType in extensionAttr.ExtensionPoints) { XmlAttributes xmlAttrs = (XmlAttributes)table[extensionPointType]; if (xmlAttrs == null) { xmlAttrs = new XmlAttributes(); table.Add(extensionPointType, xmlAttrs); } XmlElementAttribute xmlAttr = new XmlElementAttribute(extensionAttr.ElementName, extensionType); xmlAttr.Namespace = extensionAttr.Namespace; xmlAttrs.XmlElements.Add(xmlAttr); } attrs = extensionType.GetCustomAttributes(typeof(XmlFormatExtensionPrefixAttribute), false); string[] prefixes = new string[attrs.Length]; Hashtable nsDefs = new Hashtable(); for (int i = 0; i < attrs.Length; i++) { XmlFormatExtensionPrefixAttribute prefixAttr = (XmlFormatExtensionPrefixAttribute)attrs[i]; prefixes[i] = prefixAttr.Prefix; nsDefs.Add(prefixAttr.Prefix, prefixAttr.Namespace); } Array.Sort(prefixes, InvariantComparer.Default); for (int i = 0; i < prefixes.Length; i++) { namespaces.Add(prefixes[i], (string)nsDefs[prefixes[i]]); } } foreach (Type extensionPointType in table.Keys) { XmlFormatExtensionPointAttribute attr = GetExtensionPointAttribute(extensionPointType); XmlAttributes xmlAttrs = (XmlAttributes)table[extensionPointType]; if (attr.AllowElements) { xmlAttrs.XmlAnyElements.Add(new XmlAnyElementAttribute()); } overrides.Add(extensionPointType, attr.MemberName, xmlAttrs); } }
private void WriteOverriddenAttributes(string filename) { // Writing the file requires a TextWriter. TextWriter myStreamWriter = new StreamWriter(filename); // Create an XMLAttributeOverrides class. XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); // Create the XmlAttributes class. XmlAttributes attrs = new XmlAttributes(); /* Override the Student class. "Alumni" is the name * of the overriding element in the XML output. */ XmlElementAttribute attr = new XmlElementAttribute("Alumni", typeof(Graduate)); /* Add the XmlElementAttribute to the collection of * elements in the XmlAttributes object. */ attrs.XmlElements.Add(attr); /* Add the XmlAttributes to the XmlAttributeOverrides. * "Students" is the name being overridden. */ attrOverrides.Add(typeof(HighSchool.MyClass), "Students", attrs); // Create array of extra types. Type [] extraTypes = new Type[2]; extraTypes[0] = typeof(Address); extraTypes[1] = typeof(Phone); // Create an XmlRootAttribute. XmlRootAttribute root = new XmlRootAttribute("Graduates"); /* Create the XmlSerializer with the * XmlAttributeOverrides object. */ XmlSerializer mySerializer = new XmlSerializer (typeof(HighSchool.MyClass), attrOverrides, extraTypes, root, "http://www.microsoft.com"); MyClass myClass = new MyClass(); Graduate g1 = new Graduate(); g1.Name = "Jacki"; g1.ID = 1; g1.University = "Alma"; Graduate g2 = new Graduate(); g2.Name = "Megan"; g2.ID = 2; g2.University = "CM"; Student[] myArray = { g1, g2 }; myClass.Students = myArray; // Create extra information. Address a1 = new Address(); a1.City = "Ionia"; Address a2 = new Address(); a2.City = "Stamford"; Phone p1 = new Phone(); p1.Number = "555-0101"; Phone p2 = new Phone(); p2.Number = "555-0100"; Object[] o1 = new Object[2] { a1, p1 }; Object[] o2 = new Object[2] { a2, p2 }; g1.Info = o1; g2.Info = o2; mySerializer.Serialize(myStreamWriter, myClass); myStreamWriter.Close(); }
public XmlDumper(bool ignoreSensitive, R2RReader r2r, TextWriter writer, Disassembler disassembler, DumpOptions options) : base(r2r, writer, disassembler, options) { _ignoreSensitive = ignoreSensitive; XmlDocument = new XmlDocument(); _ignoredProperties = new XmlAttributeOverrides(); XmlAttributes attrs = new XmlAttributes(); attrs.XmlIgnore = _ignoreSensitive; _ignoredProperties.Add(typeof(R2RHeader), "RelativeVirtualAddress", attrs); _ignoredProperties.Add(typeof(R2RHeader), "Size", attrs); _ignoredProperties.Add(typeof(R2RImportSection), "SectionRVA", attrs); _ignoredProperties.Add(typeof(R2RImportSection), "SectionSize", attrs); _ignoredProperties.Add(typeof(R2RImportSection), "EntrySize", attrs); _ignoredProperties.Add(typeof(R2RImportSection), "SignatureRVA", attrs); _ignoredProperties.Add(typeof(R2RImportSection), "AuxiliaryDataRVA", attrs); _ignoredProperties.Add(typeof(R2RImportSection.ImportSectionEntry), "SignatureSample", attrs); _ignoredProperties.Add(typeof(R2RImportSection.ImportSectionEntry), "SignatureRVA", attrs); _ignoredProperties.Add(typeof(RuntimeFunction), "StartAddress", attrs); _ignoredProperties.Add(typeof(RuntimeFunction), "UnwindRVA", attrs); _ignoredProperties.Add(typeof(R2RSection), "RelativeVirtualAddress", attrs); _ignoredProperties.Add(typeof(R2RSection), "Size", attrs); }
// Write ProjectList member variables (XMin, XMax, YMin, Ymax, UseGeographicMap) // and ProjectLocation member variables (ID, DefinitionFile, X, Y, Description, Default) // as attributes into XML, so XamlReader can work happily. // static XmlAttributeOverrides CreateProjectListOverrides() { XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); // add root element namespace attrOverrides.Add(typeof(ProjectList), new XmlAttributes() { XmlRoot = new XmlRootAttribute() { ElementName = "ProjectList", Namespace = "clr-namespace:IS3.Core;assembly=IS3.Core" } }); // write ProjectList member variables as attributes attrOverrides.Add(typeof(ProjectList), "XMax", new XmlAttributes() { XmlAttribute = new XmlAttributeAttribute("XMax") }); attrOverrides.Add(typeof(ProjectList), "XMin", new XmlAttributes() { XmlAttribute = new XmlAttributeAttribute("XMin") }); attrOverrides.Add(typeof(ProjectList), "YMax", new XmlAttributes() { XmlAttribute = new XmlAttributeAttribute("YMax") }); attrOverrides.Add(typeof(ProjectList), "YMin", new XmlAttributes() { XmlAttribute = new XmlAttributeAttribute("YMin") }); attrOverrides.Add(typeof(ProjectList), "UseGeographicMap", new XmlAttributes() { XmlAttribute = new XmlAttributeAttribute("UseGeographicMap") }); // write ProjectLocation member variables as attributes attrOverrides.Add(typeof(ProjectLocation), "ID", new XmlAttributes() { XmlAttribute = new XmlAttributeAttribute("ID") }); attrOverrides.Add(typeof(ProjectLocation), "DefinitionFile", new XmlAttributes() { XmlAttribute = new XmlAttributeAttribute("DefinitionFile") }); attrOverrides.Add(typeof(ProjectLocation), "X", new XmlAttributes() { XmlAttribute = new XmlAttributeAttribute("X") }); attrOverrides.Add(typeof(ProjectLocation), "Y", new XmlAttributes() { XmlAttribute = new XmlAttributeAttribute("Y") }); attrOverrides.Add(typeof(ProjectLocation), "Description", new XmlAttributes() { XmlAttribute = new XmlAttributeAttribute("Description") }); attrOverrides.Add(typeof(ProjectLocation), "Default", new XmlAttributes() { XmlAttribute = new XmlAttributeAttribute("Default") }); return(attrOverrides); }
/// <summary> /// Загружает содержимое файла типа .bib /// в список изданий /// </summary> private void btnLoad_Click(object sender, EventArgs e) { Stream fileStream; OpenFileDialog openFileDialog = new OpenFileDialog(); string filePath; string fileContent = string.Empty; openFileDialog.Filter = "bib files (*.bib)|*.bib"; openFileDialog.InitialDirectory = Directory.GetCurrentDirectory(); openFileDialog.RestoreDirectory = true; if (openFileDialog.ShowDialog() == DialogResult.OK) { filePath = openFileDialog.FileName; fileStream = openFileDialog.OpenFile(); using (StreamReader streamReader = new StreamReader(fileStream)) { fileContent = streamReader.ReadToEnd(); } gridEditions.Rows.Clear(); editions.Clear(); XElement xRoot = XElement.Parse( fileContent, LoadOptions.SetLineInfo); var allNodes = xRoot.DescendantNodesAndSelf(); var nodesToSerialize = new List <XElement>(); string[] arrEditionTypes = Enum.GetNames(typeof(EditionTypes)); foreach (var node in allNodes) { if (node is XElement) { string name = ((XElement)node).Name.LocalName; if (arrEditionTypes.Contains(name)) { nodesToSerialize.Add((XElement)node); } } } XmlSerializer reader = null; Type editionType = null; IEdition edition = null; Assembly assembly = typeof(IEdition).Assembly; string typeName; List <Person> authors = new List <Person>(); string exceptionMessage = string.Empty; XmlAttributes attrs = new XmlAttributes(); attrs.XmlIgnore = true; attrs.XmlElements.Add( new XmlElementAttribute() { ElementName = "Authors" }); XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); assembly.GetTypes().ToList(). Where(x => x.IsClass && x.GetInterfaces().Contains(typeof(IEdition))). ToList().ForEach(type => { attrOverrides.Add(type, "Authors", attrs); }); foreach (var xml in nodesToSerialize) { try { typeName = "Model." + xml.Name.LocalName; editionType = assembly.GetType(typeName); reader = new XmlSerializer(editionType, attrOverrides); authors = new List <Person>(); using (TextReader stream = new StringReader(xml.ToString())) { edition = (IEdition)(Convert.ChangeType( reader.Deserialize(stream), editionType)); } using (TextReader stream = new StringReader(xml.ToString())) { XmlReaderSettings settings = new XmlReaderSettings { IgnoreComments = true, IgnoreWhitespace = true }; using (XmlReader xmlReader = XmlReader.Create(stream, settings)) { while (!xmlReader.EOF) { if (xmlReader.Name != "Person") { xmlReader.ReadToFollowing("Person"); } if (!xmlReader.EOF) { XElement person = (XElement)XNode.ReadFrom(xmlReader); Person author = new Person { FirstName = (string)person.Element("FirstName"), SecondName = (string)person.Element("SecondName"), Patronymic = (string)person.Element("Patronymic") }; authors.Add(author); } } editionType.GetProperty("Authors").SetValue( Convert.ChangeType(edition, editionType), authors); editions.Add(edition); gridEditions.Rows.Add(edition.StandartName); } } } catch (Exception ex) { exceptionMessage += "Error while loading file \n"; } } gridEditions.Update(); gridEditions.Refresh(); if (!string.IsNullOrEmpty(exceptionMessage)) { MessageBox.Show( "Error while parsing " + exceptionMessage, "Loading Error", MessageBoxButtons.OK, MessageBoxIcon.Information); } SetButtonsEnable(); } }