private void WriteInternal(Stream stream, DomObject rootDomObject, bool bTemp) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = IndentChars; settings.NewLineHandling = NewLineHandling.Replace; settings.NewLineChars = NewLineChars; using (XmlWriter writer = XmlWriter.Create(stream, settings)) { if (writer == null) { return; } writer.WriteStartDocument(); DomSchema schema = rootDomObject.Collection.Schema; WriteElement(rootDomObject, writer, schema, bTemp); writer.WriteEndDocument(); writer.Close(); } }
/// <summary> /// Reads a DomObject from the given stream /// </summary> /// <param name="stream">Stream to read</param> /// <returns>Dom tree that was read</returns> public override DomObject Read(Stream stream) { // Read project settings DomObject rootProjDomObject = ReadInternal(stream); // Try and read temporary settings file DomObject rootTempDomObject = null; try { // Path to project file string szAbsProjPath = ((FileStream)stream).Name; // Path to hidden project temporary settings file string szAbsTempPath = Path.ChangeExtension(szAbsProjPath, m_extTmp); // Read from disk if file exists if (File.Exists(szAbsTempPath)) { using (FileStream file = new FileStream(szAbsTempPath, FileMode.Open, FileAccess.Read)) { rootTempDomObject = ReadInternal(file); } } } catch (Exception ex) { SledOutDevice.OutLine(SledMessageType.Error, SledUtil.TransSub(Localization.SledSharedLoadTempSettingsFileError, new string[] { ex.Message })); } // Combine project file with temporary settings file Combine(rootProjDomObject, rootTempDomObject); return(rootProjDomObject); }
/// <summary> /// Run the logic of the copier /// </summary> /// <param name="rootProjDomObject">Project file DomObject tree</param> /// <param name="rootTempDomObject">Temporary settings file DomObject tree</param> public override void Run(DomObject rootProjDomObject, DomObject rootTempDomObject) { List <T> lstProjFiles = new List <T>(); GatherTypes(rootProjDomObject, ref lstProjFiles); List <T> lstTempFiles = new List <T>(); GatherTypes(rootTempDomObject, ref lstTempFiles); foreach (T projFile in lstProjFiles) { foreach (T tempFile in lstTempFiles) { if (m_comparer.Equals(projFile, tempFile)) { object projAttr = projFile.InternalObject.TryGetAttribute(m_attribute); object tempAttr = tempFile.InternalObject.TryGetAttribute(m_attribute); if ((projAttr != null) && (tempAttr != null)) { projFile.InternalObject.SetAttribute(m_attribute, tempAttr); } } } } }
internal static HtmlSchema FindSchema(this DomObject node) { if (node.OwnerDocument != null && node.OwnerDocument.Schema != null && node.OwnerDocument.Schema is HtmlSchema hs) { return(hs); } return(HtmlSchema.Html5); }
internal static DomObject ConvertNode(DomObject attr) { var __document = new HxlDocument(); DomElement root_article = __document.CreateElement("article"); DomObject root_article_hxlexpressionattribute = global::Carbonfrost.Commons.Hxl.HxlAttribute.Create("id", (__closure, __self__) => string.Concat((object)(__closure.Inside))); root_article.Append(root_article_hxlexpressionattribute); var conv = HxlCompilerConverter.ChooseConverter(attr); return(conv.Convert(attr, CSharpScriptGenerator.Instance)); }
private void Combine(DomObject rootProjDomObject, DomObject rootTempDomObject) { if ((rootProjDomObject == null) || (rootTempDomObject == null)) { return; } // Try and combine the two files foreach (ITempSettingsCopier copier in m_lstCopiers) { copier.Run(rootProjDomObject, rootTempDomObject); } }
/// <summary> /// Go through a DomObject tree gathering objects that can create an interface to type T /// </summary> /// <typeparam name="T">Type to create interface to using DomObject.CreateInterface()</typeparam> /// <param name="rootDomObject">DomObject tree to iterate through</param> /// <param name="lstTypes">List to store results in</param> protected virtual void GatherTypes <T>(DomObject rootDomObject, ref List <T> lstTypes) where T : class { if (rootDomObject.CanCreateInterface <T>()) { lstTypes.Add(rootDomObject.CreateInterface <T>()); } if (rootDomObject.HasChildren) { foreach (DomObject domObject in rootDomObject.Children) { GatherTypes(domObject, ref lstTypes); } } }
public void ConvertAndAppend(DomNode parent, DomObject m, IScriptGenerator gen) { var child = Convert(m, gen); if (child == null) { return; } if (object.ReferenceEquals(child, m)) { parent.Append(child); } else { parent.Append(child); } }
internal static DomNode InlineOuterText(DomDocument document, DomObject element) { var result = (HxlTextElement)document.CreateElement("c:text"); result.Data = new OuterTextVisitor().ConvertToString(element); // And make into a render work fragment // TODO Use the correct script generator // Single spaces are common - don't cause a render island to // be created for them if (result.Data == " ") { return(result); } else { return(result.ToIsland(CSharpScriptGenerator.Instance)); } }
internal static void EmitRenderingThunk(TextWriter sw, string name, DomObject component) { StringBuilder rendering = new StringBuilder(); // TODO Undesirable that expressions get serialized in EmitInstantiation // TODO This serialization logic implies that only strings can be used with expressions foreach (PropertyInfo m in Utility.ReflectGetProperties(component.GetType())) { if (m.CanWrite && m.PropertyType == typeof(string)) { // TODO Need to check more than CanWrite -- may need to check accessibility of the setter (rare) string text = (string)m.GetValue(component) ?? string.Empty; if (HxlAttributeConverter.IsExpr(text)) { CodeBuffer cb = new CodeBuffer(); RewriteExpressionSyntax.MatchVariablesAndEmit(cb, text); rendering.AppendFormat(" {2}.{0} = {1};", m.Name, cb, name); rendering.AppendLine(); } } } var additional = component.Annotations <ExpressionInitializers>(); foreach (ExpressionInitializers m in additional) { rendering.AppendFormat(" {2}.{0} = {1};", m.Member.Name, m.Expression, name); rendering.AppendLine(); } // TODO Use of __self__ is a hack (will it actually be used?) if (rendering.Length > 0) { sw.WriteLine("{0}.Rendering = (__context, __self__) => {{", name); sw.WriteLine(" dynamic __closure = __context;"); sw.Write(rendering); sw.WriteLine("};"); } }
internal static HxlCompilerConverter ChooseConverter(DomObject node) { switch (node.NodeType) { case DomNodeType.Element: return(HxlElementConverter.GetElementConverter((DomElement)node)); case DomNodeType.Attribute: return(HxlAttributeConverter.GetAttributeConverter((DomAttribute)node)); case DomNodeType.ProcessingInstruction: return(HxlProcessingInstructionConverter.GetProcessingInstructionConverter((DomProcessingInstruction)node)); case DomNodeType.Text: // TODO Could be noop if entity ref nodes were processed (design, perf) // Right now, inlining is the cleanest way to handle entities correctly return(Inline); case DomNodeType.DocumentType: default: return(Noop); } }
/// <summary> /// Writes the DomObject to the given stream /// </summary> /// <param name="stream">Stream to write to</param> /// <param name="rootDomObject">Dom tree to write</param> public override void Write(Stream stream, DomObject rootDomObject) { // Write project settings WriteInternal(stream, rootDomObject, false); // Create stream to write the temporary settings file or if we can't then do nothing try { // Path to project file string szAbsProjPath = ((FileStream)stream).Name; // Path to hidden project temporary settings file string szAbsTempPath = Path.ChangeExtension(szAbsProjPath, m_extTmp); // Make it writeable if it already exists if (File.Exists(szAbsTempPath)) { File.SetAttributes(szAbsTempPath, FileAttributes.Normal); } // Write to disk using (FileStream file = new FileStream(szAbsTempPath, FileMode.Create, FileAccess.Write)) { WriteInternal(file, rootDomObject, true); } // Make hidden if (File.Exists(szAbsTempPath)) { File.SetAttributes(szAbsTempPath, FileAttributes.Hidden); } } catch (Exception ex) { SledOutDevice.OutLine(SledMessageType.Error, SledUtil.TransSub(Localization.SledSharedSaveTempSettingsFileError, new string[] { ex.Message })); } }
private DomObject ReadInternal(Stream stream) { DomObject rootDomObject; using (XmlReader reader = XmlReader.Create(stream)) { reader.MoveToContent(); string ns = reader.NamespaceURI; XmlQualifiedName rootElementName = new XmlQualifiedName(reader.LocalName, ns); DomMetaElement rootElement = DomSchemaRegistry.GetRootElement(rootElementName); if (rootElement == null) { throw new InvalidOperationException("Unknown root element"); } rootDomObject = new DomObject(rootElement); ReadElement(rootDomObject, reader); reader.Close(); } return(rootDomObject); }
public string ConvertToString(DomObject node) { Visit(node); return(_sb.ToString()); }
public static void Retain(this DomObject element) { element.AddAnnotation(HxlAnnotations.Retained); }
/// <summary> /// Read element /// </summary> /// <param name="domObject"></param> /// <param name="reader"></param> protected void ReadElement(DomObject domObject, XmlReader reader) { DomComplexType type = domObject.Type; // Read attributes int required = type.RequiredAttributes; while (reader.MoveToNextAttribute()) { if (reader.Prefix == string.Empty || reader.LookupNamespace(reader.Prefix) == type.Name.Namespace) { DomMetaAttribute metaAttribute = type.GetAttribute(reader.LocalName); if (metaAttribute != null) { object value = metaAttribute.Type.Convert(reader.Value); domObject.SetAttribute(metaAttribute.Name, value); if (metaAttribute.Required) { required--; } } } } if (required != 0) { throw new InvalidOperationException("Missing required attribute"); } reader.MoveToElement(); if (!reader.IsEmptyElement) { // Read child elements while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { // look up metadata for this element DomMetaElement metaElement = type.GetChild(reader.LocalName); if (metaElement != null) { DomObject child = CreateElement(reader, metaElement); ReadElement(child, reader); // At this point, child is a fully populated sub-tree domObject.AddChild(metaElement, child); } else { reader.Skip(); } } else if (reader.NodeType == XmlNodeType.Text) { if (type.ValueType != null) { domObject.Value = type.ValueType.Convert(reader.Value); } } else if (reader.NodeType == XmlNodeType.EndElement) { break; } } } reader.MoveToContent(); }
public void Attaching(DomObject instance) { LastAttachingArguments = instance; AttachingCallCount++; }
/// <summary> /// Write element /// </summary> /// <param name="element"></param> /// <param name="writer"></param> /// <param name="schema"></param> /// <param name="bTemp"></param> protected void WriteElement(DomObject element, XmlWriter writer, DomSchema schema, bool bTemp) { // Test if the element should be saved or not if (!bTemp && !element.CanCreateInterface <ISledProjectFilesSaveableType>()) { return; } string elemNs = element.MetaElement.QualifiedName.Namespace; string elemPrefix; // Is this the root DomObject? if (schema != null) { elemPrefix = schema.GetPrefix(elemNs) ?? GeneratePrefix(elemNs); writer.WriteStartElement(elemPrefix, element.MetaElement.Name, elemNs); // Define the xsi namespace writer.WriteAttributeString("xmlns", "xsi", null, XmlSchema.InstanceNamespace); // Define schema namespaces foreach (XmlQualifiedName name in schema.Namespaces) { if (name.Name != elemPrefix) // don't redefine the element namespace { writer.WriteAttributeString("xmlns", name.Name, null, name.Namespace); } } } else { // Not the root, so all schema namespaces have been defined elemPrefix = writer.LookupPrefix(elemNs) ?? GeneratePrefix(elemNs); writer.WriteStartElement(elemPrefix, element.MetaElement.Name, elemNs); } // Write type name if this is a polymorphic type DomComplexType elementType = element.Type; if (element.MetaElement.Type != elementType) { string typeName = elementType.Name.Name; string typeNs = elementType.Name.Namespace; string typePrefix = writer.LookupPrefix(typeNs); if (typePrefix == null) { typePrefix = GeneratePrefix(typeNs); writer.WriteAttributeString("xmlns", typePrefix, null, typeNs); } if (typePrefix != string.Empty) { typeName = typePrefix + ":" + typeName; } writer.WriteAttributeString("xsi", "type", XmlSchema.InstanceNamespace, typeName); } // When writing project file we build a list of attributes to NOT save List <string> lstAttrsDontSave = new List <string>(); // Do some stuff if writing project file if (!bTemp) { // Get all annotations (including base type annotations [and their base type annotations etc.]) List <XmlNode> lstAnnotations = new List <XmlNode>(); GetAllAnnotations(element.Type, ref lstAnnotations); // Go through pulling out which attributes to not save based on the annotation foreach (XmlNode annotation in lstAnnotations) { // Do something if it's a "dont save" annotation! if (string.Compare(annotation.Name, DontSaveAnnotation, true) == 0) { XmlNode node = annotation.Attributes.GetNamedItem("name"); if (node != null) { string szAttribute = node.Value; if (!lstAttrsDontSave.Contains(szAttribute)) { lstAttrsDontSave.Add(szAttribute); } } } } } // Write normal attributes foreach (DomMetaAttribute attribute in elementType.Attributes) { // Do some stuff if writing project file if (!bTemp && (lstAttrsDontSave.Count > 0) && !string.IsNullOrEmpty(attribute.Name)) { if (lstAttrsDontSave.Contains(attribute.Name)) { continue; } } object value = element.GetAttribute(attribute); if (attribute.Required) { if (value == null) { throw new InvalidOperationException("missing attribute"); } writer.WriteAttributeString(attribute.Name, attribute.Type.Convert(value)); } else if (value != null && value != attribute.Type.GetDefault()) { writer.WriteAttributeString(attribute.Name, attribute.Type.Convert(value)); } } // Write element value if (element.Value != null && element.Value != elementType.ValueType.GetDefault()) { writer.WriteString(elementType.ValueType.Convert(element.Value)); } // write child elements foreach (DomMetaElement elem in elementType.Children) { foreach (DomObject child in element.GetChildren(elem.Name)) { WriteElement(child, writer, null, bTemp); } } writer.WriteEndElement(); }
public sealed override DomObject Convert(DomObject node, IScriptGenerator gen) { return(Convert(node.OwnerDocument, (DomProcessingInstruction)node)); }
public sealed override DomObject Convert(DomObject node, IScriptGenerator gen) { return(Convert(node.OwnerDocument, (DomElement)node, gen)); }
/// <summary> /// Run the logic of the copier /// </summary> /// <param name="rootProjDomObject">Project file DomObject tree</param> /// <param name="rootTempDomObject">Temporary settings file DomObject tree</param> public abstract void Run(DomObject rootProjDomObject, DomObject rootTempDomObject);
/// <summary> /// Run the logic of the copier /// </summary> /// <param name="rootProjDomObject">Project file DomObject tree</param> /// <param name="rootTempDomObject">Temporary settings file DomObject tree</param> public override void Run(DomObject rootProjDomObject, DomObject rootTempDomObject) { List <T> lstProjFiles = new List <T>(); GatherTypes(rootProjDomObject, ref lstProjFiles); List <T> lstTempFiles = new List <T>(); GatherTypes(rootTempDomObject, ref lstTempFiles); foreach (T projFile in lstProjFiles) { foreach (T tempFile in lstTempFiles) { if (m_comparer.Equals(projFile, tempFile)) { foreach (DomObject domObject in tempFile.InternalObject.Children) { if (domObject.CanCreateInterface <TU>()) { // Search for element to add child to DomMetaElement metaElement = null; foreach (DomMetaElement elem in projFile.InternalObject.Type.Children) { if (elem.Type == domObject.Type) { metaElement = elem; break; } if (!elem.Type.IsAssignableFrom(domObject.Type)) { continue; } metaElement = elem; break; } if (metaElement != null) { bool bAdd = true; if (m_dupComparer != null) { // Check for duplicates first! bool bDuplicate = false; foreach (DomObject d in projFile.InternalObject.Children) { if (!d.CanCreateInterface <TU>()) { continue; } bool bEquals = m_dupComparer.Equals( d.CreateInterface <TU>(), domObject.CreateInterface <TU>()); if (!bEquals) { continue; } bDuplicate = true; break; } // Don't add duplicates bAdd = !bDuplicate; } // Copy over to project (if it isn't already there) if (bAdd && !domObject.CanCreateInterface <ISledProjectFilesSaveableSingletonType>()) { DomObject domClone = domObject.Clone(); projFile.InternalObject.AddChild(metaElement, domClone); } } } } } } } }
void IDomObjectReferenceLifecycle.Attaching(DomObject instance) { Attaching((DomAttribute)instance); }
public abstract DomObject Convert(DomObject node, IScriptGenerator gen);
public override DomObject Convert(DomObject node, IScriptGenerator gen) { return(node); }
// - Element is NOT an ElementFragment // - Element contains no AttributeFragments // - Element has no children OR has descendents which are all marked as inlining public override DomObject Convert(DomObject node, IScriptGenerator gen) { return(InlineOuterText(node.OwnerDocument, node)); }