public void SameNamespaceSameNameAttributes() { var a = new XAttribute("{Namespace}Name", "a"); var b = new XAttribute("{Namespace}Name", "b"); Assert.Same(a.Name.Namespace, b.Name.Namespace); Assert.Same(a.Name, b.Name); }
public void CanUseAreControlsValid() { //asign var controlManager = new ControlManager(); var xForm = new XForm(); xForm.Root = new XContainer { Name = "BaseContainer" }; var xAttribute = new XAttribute<string>("StringAttribute") { Name = "StringAttribute", Value = "StringAttribute", Use = XAttributeUse.Required }; var xContainer = new XContainer { Name = "ChildContainer", Value = "ChildContainerValue", ParentContainer = xForm.Root, MaxOccurs = 1234, MinOccurs = 0 }; xContainer.Attributes.Add(xAttribute); var xElement = new XElement { Name = "Element", Value = "ElementValue" }; xContainer.Elements.Add(xElement); xForm.Root.Attributes.Add(xAttribute); xForm.Root.Containers.Add(xContainer); xForm.Root.Elements.Add(xElement); xContainer.Value = "test"; //action controlManager.GetGroupBoxGui(xForm.Root, xForm.Root); var areControlsValid = controlManager.AreControlsValid(); //assert Assert.False(areControlsValid); }
public static bool? ToBool(XAttribute attribute) { if (attribute == null) { return null; } return bool.Parse(attribute.Value); }
public void GetControlForXAttributeTypeDateTime() { //asign var xAttribute = new XAttribute<DateTime>(DateTime.Now); xAttribute.Name = "xAttribute"; var controlFactory = new ControlFactory(); //action var control = controlFactory.GetControl(xAttribute); //assert Assert.NotNull(control); Assert.AreEqual(control.Name, xAttribute.Name); Assert.True(control.Tag is XAttribute<DateTime>); Assert.True(control is DateTimePicker); }
public void GetControlForXAttributeTypeString() { //asign var xAttribute = new XAttribute<string>("default"); xAttribute.Name = "xAttribute"; var controlFactory = new ControlFactory(); //action var control = controlFactory.GetControl(xAttribute); //assert Assert.NotNull(control); Assert.AreEqual(control.Name, xAttribute.Name); Assert.True(control.Tag is XAttribute<string>); Assert.True(control is TextBox); }
public void GetControlForXAttributeTypeInteger() { //asign var xAttribute = new XAttribute<int>(1); xAttribute.Name = "xAttribute"; var controlFactory = new ControlFactory(); //action var control = controlFactory.GetControl(xAttribute); //assert Assert.NotNull(control); Assert.AreEqual(control.Name, xAttribute.Name); Assert.True(control.Tag is XAttribute<int>); Assert.True(control is NumericUpDown); }
public void GetControlForXAttributeTypeBoolean() { //asign var xAttribute = new XAttribute<bool>(false); xAttribute.Name = "xAttribute"; var controlFactory = new ControlFactory(); //action var control = controlFactory.GetControl(xAttribute); //assert Assert.NotNull(control); Assert.AreEqual(control.Name, xAttribute.Name); Assert.True(control.Tag is XAttribute<bool>); Assert.True(control is CheckBox); }
void InjectImport() { // <Import Project="$(SolutionDir)\Tools\Fody\Fody.targets" /> var exists = xDocument .BuildDescendants("Import") .Any(x => { var xAttribute = x.Attribute("Project"); return xAttribute != null && xAttribute.Value.EndsWith("Fody.targets", StringComparison.InvariantCultureIgnoreCase); }); if (exists) { return; } var importAttribute = new XAttribute("Project", Path.Combine(FodyToolsDirectory, "Fody.targets")); xDocument.Root.Add(new XElement(MsBuildXmlExtensions.BuildNamespace + "Import", importAttribute)); }
void InjectImport() { // <Import Project="$(SolutionDir)\Tools\Pepita\PepitaGet.targets" /> var imports = xDocument.BuildDescendants("Import").ToList(); var exists = imports .Any(x => { var xAttribute = x.Attribute("Project"); return xAttribute != null && xAttribute.Value.EndsWith("PepitaGet.targets"); }); if (exists) { return; } var importAttribute = new XAttribute("Project", Path.Combine(PepitaGetToolsDirectory, "PepitaGet.targets")); xDocument.Root.Add(new XElement(MsBuildXmlExtensions.BuildNamespace + "Import", importAttribute)); }
public void NazwaElementuTest() { Diff diff = new Diff("<a/>", "<a/>", 33, false, true); XElement root = new XElement("Root"); XAttribute atrybut = new XAttribute("a", "wartosc"); Assert.AreEqual(Compare.NazwaElementu(root), "Root"); Assert.AreEqual(Compare.NazwaElementu(atrybut), "a"); XNamespace aw = "http://www.test.com"; root = new XElement(aw + "Root"); atrybut = new XAttribute(aw + "a", "wartosc"); Assert.AreEqual(Compare.NazwaElementu(root), "Root"); Assert.AreEqual(Compare.NazwaElementu(atrybut), "a"); diff=new Diff("<a/>", "<a/>", 33, true, true); root = new XElement(aw + "Root"); atrybut = new XAttribute(aw + "a", "wartosc"); Assert.AreEqual(Compare.NazwaElementu(root), "{http://www.test.com}Root"); Assert.AreEqual(Compare.NazwaElementu(atrybut), "{http://www.test.com}a"); }
public void CanUseGenerateGui() { //asign var controlManager = new ControlManager(); var xForm = new XForm(); xForm.Root = new XContainer { Name = "BaseContainer" }; var xAttribute = new XAttribute<string>(string.Empty) { Name = "StringAttribute", Value = "StringAttribute", Use = XAttributeUse.Required }; var xContainer = new XContainer { Name = "ChildContainer", Value = "ChildContainerValue", ParentContainer = xForm.Root, MaxOccurs = 1234, MinOccurs = 0 }; xContainer.Attributes.Add(xAttribute); var xElement = new XElement { Name = "Element", Value = "ElementValue" }; xContainer.Elements.Add(xElement); xForm.Root.Attributes.Add(xAttribute); xForm.Root.Containers.Add(xContainer); xForm.Root.Elements.Add(xElement); //action var groupBoxGui = controlManager.GetGroupBoxGui(xForm.Root, xForm.Root); //assert Assert.NotNull(groupBoxGui); }
public void CanParseXFormFromXmlFileDocumentumArchivageSettingsXsd() { //asign var xmlWriter = new XmlWriter(); var xForm = new XForm(); xForm.Root = new XContainer { Name = "BaseContainer" }; var xAttribute = new XAttribute<string>(string.Empty) { Name = "StringAttribute", Value = "StringAttribute" }; var xContainer = new XContainer { Name = "ChildContainer", Value = "ChildContainerValue", ParentContainer = xForm.Root }; xContainer.Attributes.Add(xAttribute); var xElement = new XElement { Name = "Element", Value = "ElementValue" }; xContainer.Elements.Add(xElement); xForm.Root.Attributes.Add(xAttribute); xForm.Root.Containers.Add(xContainer); xForm.Root.Elements.Add(xElement); var fileStream = new FileStream(@"testXml.txt", FileMode.OpenOrCreate); //action xmlWriter.WriteXFormToXmlFile(fileStream, xForm); //assert var xml = File.ReadAllText(@"testXml.txt"); var resultXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" + "<BaseContainer xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" StringAttribute=\"StringAttribute\">" + "\r\n <Element>ElementValue</Element>" + "\r\n <ChildContainer StringAttribute=\"StringAttribute\">ChildContainerValue" + "<Element>ElementValue</Element>" + "</ChildContainer>" + "\r\n</BaseContainer>"; Assert.AreEqual(xml, resultXml); }
public override State PushChar (char c, IParseContext context, ref string rollback) { XAttribute att = context.Nodes.Peek () as XAttribute; //state has just been entered if (context.CurrentStateLength == 1) { if (context.PreviousState is XmlNameState) { //error parsing name if (!att.IsNamed) { context.Nodes.Pop (); rollback = string.Empty; return Parent; } context.StateTag = GETTINGEQ; } else if (context.PreviousState is XmlAttributeValueState) { //Got value, so end attribute context.Nodes.Pop (); att.End (context.LocationMinus (1)); IAttributedXObject element = (IAttributedXObject) context.Nodes.Peek (); element.Attributes.AddAttribute (att); rollback = string.Empty; return Parent; } else { //starting a new attribute Debug.Assert (att == null); Debug.Assert (context.StateTag == NAMING); att = new XAttribute (context.LocationMinus (1)); context.Nodes.Push (att); rollback = string.Empty; return XmlNameState; } } if (context.StateTag == GETTINGEQ) { if (char.IsWhiteSpace (c)) { return null; } if (c == '=') { context.StateTag = GETTINGVAL; return null; } context.LogError ("Expecting = in attribute, got '" + c + "'."); } else if (context.StateTag == GETTINGVAL) { if (char.IsWhiteSpace (c)) { return null; } rollback = string.Empty; return AttributeValueState; } else if (c != '<') { //parent handles message for '<' context.LogError ("Unexpected character '" + c + "' in attribute."); } if (att != null) context.Nodes.Pop (); rollback = string.Empty; return Parent; }
public static Texture2D LoadTexture(XAttribute textureAtt, XElement elemtype, Color defaultColor, bool linear = false) { if (textureAtt == null) return CreateFlatTexture(defaultColor); string texturePath = Path.Combine(Path.GetDirectoryName(new Uri(elemtype.BaseUri).LocalPath), textureAtt.Value); texturePath = Path.GetFullPath(texturePath); if (!File.Exists(texturePath)) { Debug.LogError("File not found: " + texturePath); return CreateFlatTexture(defaultColor); } byte[] patternData = File.ReadAllBytes(texturePath); Texture2D texture = new Texture2D(2, 2, TextureFormat.ARGB32, false, linear); texture.LoadImage(patternData); GameSettings.ClampToMaxSize(texture); texture.name = texturePath; if (texture.width * 4 <= GameSettings.Instance.rendering.maxTextureSize && texture.height * 4 <= GameSettings.Instance.rendering.maxTextureSize) { texture = HqxSharp.Scale4(texture); } else if (texture.width * 3 <= GameSettings.Instance.rendering.maxTextureSize && texture.height * 3 <= GameSettings.Instance.rendering.maxTextureSize) { texture = HqxSharp.Scale3(texture); } else if (texture.width * 2 <= GameSettings.Instance.rendering.maxTextureSize && texture.height * 2 <= GameSettings.Instance.rendering.maxTextureSize) { texture = HqxSharp.Scale2(texture); } return texture; }
private static TimeSpan AttributeToDuration(XAttribute attribute) { return(attribute == null ? TimeSpan.Zero : StringToTimeSpan(attribute.Value)); }
protected override CompletionDataList GetAttributeValueCompletions(IAttributedXObject attributedOb, XAttribute att) { CompletionDataList list = new CompletionDataList (); CompletionContext ctx = GetCompletionContext (1); if (ctx != null) { ctx.SetCompletionAction (CompletionAction.AttributeValue, att.Name.Name); ctx.AddCompletionData (list); } return list; }
internal void Load(XElement xAnnotation) { if (xAnnotation == null) { throw new ArgumentNullException("xAnnotation"); } if (xAnnotation.Name.LocalName != GetElementName()) { throw new ArgumentException("Element of wrong type passed", "xAnnotation"); } content.Clear(); IEnumerable <XElement> xItems = xAnnotation.Elements(); foreach (var xItem in xItems) { switch (xItem.Name.LocalName) { case ParagraphItem.Fb2ParagraphElementName: ParagraphItem paragraph = new ParagraphItem(); try { paragraph.Load(xItem); content.Add(paragraph); } catch (Exception) { } break; case PoemItem.Fb2PoemElementName: PoemItem poem = new PoemItem(); try { poem.Load(xItem); content.Add(poem); } catch (Exception) { } break; case CiteItem.Fb2CiteElementName: CiteItem cite = new CiteItem(); try { cite.Load(xItem); content.Add(cite); } catch (Exception) { } break; case SubTitleItem.Fb2SubtitleElementName: SubTitleItem subtitle = new SubTitleItem(); try { subtitle.Load(xItem); content.Add(subtitle); } catch (Exception) { } break; case TableItem.Fb2TableElementName: TableItem table = new TableItem(); try { table.Load(xItem); content.Add(table); } catch (Exception) { } break; case EmptyLineItem.Fb2EmptyLineElementName: EmptyLineItem eline = new EmptyLineItem(); content.Add(eline); break; default: Debug.WriteLine(string.Format("AnnotationItem:Load - invalid element <{0}> encountered in annotation ."), xItem.Name.LocalName); break; } } ID = null; XAttribute xID = xAnnotation.Attribute("id"); if ((xID != null) && (xID.Value != null)) { ID = xID.Value; } }
protected virtual Task<CompletionDataList> GetAttributeValueCompletions (IAttributedXObject attributedOb, XAttribute att, CancellationToken token) { return Task.FromResult (new CompletionDataList ()); }
private float ReadNumber(XAttribute a) => ReadNumber(a?.Value);
private bool ReadSettings() { try { if (!File.Exists(PluginSettingsFilePath)) { throw new FileNotFoundException("ChatBot.xml not found.", PluginSettingsFilePath); } Util.WaitUntilReadable(PluginSettingsFilePath, 10000); XDocument doc = XDocument.Load(PluginSettingsFilePath); if (doc.Root == null || doc.Root.Name != "Settings") { throw new InvalidOperationException("Could not find settings-root-node in ChatBot.xml."); } Botname = "[ChatBot] "; XElement botnameElement = doc.Root.Element("Botname"); if (botnameElement != null) { Botname = botnameElement.Value; } Answers = new Dictionary <string, ChatBotAnswer>(); foreach (XElement phraseElement in doc.Root.Descendants("Phrase")) { XAttribute phraseAttribute = phraseElement.Attribute("values"); XAttribute answerAttribute = phraseElement.Attribute("answer"); XAttribute wisperAttribute = phraseElement.Attribute("wisper"); if (answerAttribute == null || phraseAttribute == null) { continue; } string answer = answerAttribute.Value.Trim(); bool wisper = (wisperAttribute != null) && (string.Compare(wisperAttribute.Value, "true", true) == 0); if (answer.IsNullOrTimmedEmpty()) { continue; } string[] phrases = phraseAttribute.Value.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); foreach (string phrase in phrases) { if (phrase.IsNullOrTimmedEmpty()) { continue; } Answers[phrase.Trim().ToLower()] = new ChatBotAnswer(answer, wisper); } } Phrases = Answers.Keys.OfType <string>().ToList().ToArray(); return(true); } catch (Exception ex) { Logger.WarnToUI("Could not read Chatbot.xml! See Error-Log for detailed error description!", ex); Logger.Warn("The following exception occured during reading Chatbot.xml", ex); return(false); } }
private void ParseFile() { XElement root = XElement.Load(FileName); //For all version of Vixen the Time, EventPeriod, EventValues and Audio are at the root level, //so just select them. SeqLengthInMills = Int32.Parse(root.Element("Time").Value); EventPeriod = Int32.Parse(root.Element("EventPeriodInMilliseconds").Value); EventData = Convert.FromBase64String(root.Element("EventValues").Value); //Someone may have decided to not use audio so we need to check for that as well. var songElement = root.Elements("Audio").SingleOrDefault(); if (songElement != null) { SongFileName = root.Element("Audio").Attribute("filename").Value; } //if the sequence is flattened then the profile element will not exists so lets check for it. var profileElement = root.Elements("Profile").SingleOrDefault(); if (profileElement != null) { ProfileName = root.Element("Profile").Value; } //If in a rare case a profile name is set AND we have channels, discard the profile name so the import will use the sequence channel data if (!String.IsNullOrEmpty(ProfileName) && root.Element("Channels").HasElements) { ProfileName = string.Empty; } foreach (XElement e in root.Elements("Channels").Elements("Channel")) { XAttribute nameAttrib = e.Attribute("name"); XAttribute colorAttrib = e.Attribute("color"); //This exists in the 2.5.x versions of Vixen //<Channel name="Mini Tree Red 1" color="-65536" output="0" id="5576725746726704001" enabled="True" /> if (nameAttrib != null) { CreateMappingList(e, 2); } //This exists in the older versions //<Channel color="-262330" output="0" id="633580705216250000" enabled="True">FenceIcicles-1</Channel> else if (colorAttrib != null) { CreateMappingList(e, 1); } } if (!String.IsNullOrEmpty(SongFileName)) { MessageBox.Show( string.Format("Audio File {0} is associated with this sequence, please select the location of the audio file.", SongFileName), "Select Audio Location", MessageBoxButtons.OK, MessageBoxIcon.Information); } var dialog = new OpenFileDialog { Multiselect = false, Title = string.Format("Open Vixen 2.x Audio [{0}]", SongFileName), Filter = "Audio|*.mp3|All Files (*.*)|*.*", RestoreDirectory = true, InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Vixen\Audio" }; using (dialog) { if (dialog.ShowDialog() == DialogResult.OK) { SongFileName = dialog.SafeFileName; SongPath = Path.GetDirectoryName(dialog.FileName); } } //check to see if the ProfileName is not null, if it isn't lets notify the user so they //can let us load the data if (!String.IsNullOrEmpty(ProfileName)) { MessageBox.Show( string.Format("Vixen {0}.pro is associated with this sequence, please select the location of the profile.", ProfileName), "Select Profile Location", MessageBoxButtons.OK, MessageBoxIcon.Information); dialog = new OpenFileDialog { Multiselect = false, Title = string.Format("Open Vixen 2.x Profile [{0}]", ProfileName), Filter = "Profile|*.pro", RestoreDirectory = true, InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Vixen\Profiles" }; using (dialog) { if (dialog.ShowDialog() == DialogResult.OK) { ProfilePath = Path.GetDirectoryName(dialog.FileName); ProfileName = dialog.SafeFileName; root = null; root = XElement.Load(dialog.FileName); foreach (XElement e in root.Elements("ChannelObjects").Elements("Channel")) { XAttribute nameAttrib = e.Attribute("name"); XAttribute colorAttrib = e.Attribute("color"); //This exists in the 2.5.x versions of Vixen //<Channel name="Mini Tree Red 1" color="-65536" output="0" id="5576725746726704001" enabled="True" /> if (nameAttrib != null) { CreateMappingList(e, 2); } //This exists in the older versions //<Channel color="-262330" output="0" id="633580705216250000" enabled="True">FenceIcicles-1</Channel> else if (colorAttrib != null) { CreateMappingList(e, 1); } } } } } else //if the profile name is null or empty then the sequence must have been flattened so indicate that. { ProfileName = "Sequence has been flattened no profile is available"; } // These calculations could have been put in the properties, but then it gets confusing to debug because of all the jumping around. TotalEventsCount = Convert.ToInt32(Math.Ceiling((double)(SeqLengthInMills / EventPeriod))); ; ElementCount = EventData.Length / TotalEventsCount; EventsPerElement = EventData.Length / ElementCount; // are we seeing an error in the mappings counts? if (mappings.Count != ElementCount) { Logging.Error("ParseFile: Actual mappings (" + mappings.Count + ") and calculated mappings (" + ElementCount + ") do not match. Using the Actual mappings value."); ElementCount = mappings.Count; } // end fix error in the V2 element reporting calculations } // ParseFile
public static XElement RemoveNamespaceAttributes(string[] inScopePrefixes, XNamespace[] inScopeNs, List <XAttribute> attributes, XElement e) { checked { if (e != null) { XAttribute xAttribute = e.FirstAttribute; while (xAttribute != null) { XAttribute nextAttribute = xAttribute.NextAttribute; if (xAttribute.IsNamespaceDeclaration) { XNamespace xNamespace = xAttribute.Annotation <XNamespace>(); string localName = xAttribute.Name.LocalName; if ((object)xNamespace != null) { if ((inScopePrefixes != null && inScopeNs != null) ? true : false) { int num = inScopePrefixes.Length - 1; int num2 = num; int num3 = 0; while (true) { int num4 = num3; int num5 = num2; if (num4 > num5) { break; } string value = inScopePrefixes[num3]; XNamespace xNamespace2 = inScopeNs[num3]; if (localName.Equals(value)) { if (xNamespace == xNamespace2) { xAttribute.Remove(); } xAttribute = null; break; } num3++; } } if (xAttribute != null) { if (attributes != null) { int num6 = attributes.Count - 1; int num7 = num6; int num8 = 0; while (true) { int num9 = num8; int num5 = num7; if (num9 > num5) { break; } XAttribute xAttribute2 = attributes[num8]; string localName2 = xAttribute2.Name.LocalName; XNamespace xNamespace3 = xAttribute2.Annotation <XNamespace>(); if ((object)xNamespace3 != null && localName.Equals(localName2)) { if (xNamespace == xNamespace3) { xAttribute.Remove(); } xAttribute = null; break; } num8++; } } if (xAttribute != null) { xAttribute.Remove(); attributes.Add(xAttribute); } } } } xAttribute = nextAttribute; } } return(e); } }
private static string Value(XAttribute X) { return(X != null ? X.Value : ""); }
private void UpdateInput(XElement element, string version, string idField, XElement nameElement, bool fromXml) { try { var isXmlUpdated = false; var objectType = element?.Name.LocalName; if (string.IsNullOrEmpty(objectType)) return; var uri = GetUriFromXml(element, version, objectType)?.Uri; Model.Store.ContentType = !string.IsNullOrEmpty(uri) ? new EtpUri(uri).ContentType : new EtpContentType(EtpContentTypes.Witsml141.Family, version, objectType); var idAttribute = element.Attribute(idField); if (idAttribute != null) { if (!IsUuidMatch(Model.Store?.Uuid, idAttribute.Value)) if (fromXml) Model.Store.Uuid = idAttribute.Value; else { idAttribute.Value = Model.Store.Uuid; isXmlUpdated = true; } } else if (!string.IsNullOrWhiteSpace(Model.Store.Uuid)) { idAttribute = new XAttribute(idField, Model.Store.Uuid); element.Add(idAttribute); isXmlUpdated = true; } if (nameElement != null) { if (!IsNameMatch(Model.Store?.Name, nameElement.Value)) if (fromXml) Model.Store.Name = nameElement.Value; else nameElement.Value = Model.Store.Name; } uri = GetUriFromXml(element, version, objectType)?.Uri; if (!IsUriMatch(Model.Store.Uri, uri)) if (fromXml || isXmlUpdated) Model.Store.Uri = uri; else { var etpUri = GetEtpUriFromInputUri(); etpUri.GetObjectIds().ForEach(x => { var xAttribute = etpUri.ObjectType == x.ObjectType ? element.Attribute(idField) : element.Attribute(idField + x.ObjectType.ToPascalCase()); if (xAttribute != null) { xAttribute.Value = x.ObjectId; if (etpUri.ObjectType == x.ObjectType) Model.Store.Uuid = x.ObjectId; } }); } } catch { // ignore } }
private float?ReadOptionalNumber(XAttribute a) => a == null ? (float?)null : ReadNumber(a.Value);
public override State PushChar (char c, IParseContext context, ref string rollback) { XAttribute att = context.Nodes.Peek () as XAttribute; if (c == '<') { //parent handles message if (att != null) context.Nodes.Pop (); rollback = string.Empty; return Parent; } //state has just been entered if (context.CurrentStateLength == 1) { if (context.PreviousState is XmlNameState) { Debug.Assert (att.IsNamed); context.StateTag = GETTINGEQ; } else if (context.PreviousState is XmlAttributeValueState) { //Got value, so end attribute context.Nodes.Pop (); att.End (context.LocationMinus (1)); IAttributedXObject element = (IAttributedXObject) context.Nodes.Peek (); element.Attributes.AddAttribute (att); rollback = string.Empty; return Parent; } else { //starting a new attribute Debug.Assert (att == null); Debug.Assert (context.StateTag == NAMING); att = new XAttribute (context.LocationMinus (1)); context.Nodes.Push (att); rollback = string.Empty; return XmlNameState; } } if (c == '>') { context.LogWarning ("Attribute ended unexpectedly with '>' character."); if (att != null) context.Nodes.Pop (); rollback = string.Empty; return Parent; } if (context.StateTag == GETTINGEQ) { if (char.IsWhiteSpace (c)) { return null; } else if (c == '=') { context.StateTag = GETTINGVAL; return null; } } else if (context.StateTag == GETTINGVAL) { if (char.IsWhiteSpace (c)) { return null; } else if (c== '"') { return DoubleQuotedAttributeValueState; } else if (c == '\'') { return SingleQuotedAttributeValueState; } else if (char.IsLetterOrDigit (c)) { rollback = string.Empty; return UnquotedAttributeValueState; } } if (Char.IsLetterOrDigit (c) || char.IsPunctuation (c) || char.IsWhiteSpace (c)) { string err; if (context.StateTag == GETTINGEQ) context.LogError ("Expecting = in attribute, got " + c + "."); else if (context.StateTag == GETTINGVAL) context.LogError ("Expecting attribute value, got " + c + "."); else context.LogError ("Unexpected character '" + c + "' in attribute."); if (att != null) context.Nodes.Pop (); rollback = string.Empty; return Parent; } rollback = string.Empty; return Parent; }
private static bool?AttributeToNullableBool(XAttribute attribute, bool?defaultValue) { return(string.IsNullOrEmpty(attribute?.Value) ? defaultValue : Convert.ToBoolean(attribute.Value)); }
private static ParseOptions GetParseOptionsWithFeatures(ParseOptions parseOptions, XAttribute featuresAttribute) { var entries = featuresAttribute.Value.Split(';'); var features = entries.Select(x => { var split = x.Split('='); var key = split[0]; var value = split.Length == 2 ? split[1] : "true"; return(new KeyValuePair <string, string>(key, value)); }); return(parseOptions.WithFeatures(features)); }
/// <summary> /// See <see cref="ICompilerExtension.ParseAttribute(Intermediate, IntermediateSection, XElement, XAttribute, IDictionary{String, String})"/> /// </summary> public virtual void ParseAttribute(Intermediate intermediate, IntermediateSection section, XElement parentElement, XAttribute attribute, IDictionary <string, string> context) { this.ParseHelper.UnexpectedAttribute(parentElement, attribute); }
private static ParseOptions GetParseOptionsWithLanguageVersion(string language, ParseOptions parseOptions, XAttribute languageVersionAttribute) { if (language == LanguageNames.CSharp) { var languageVersion = (CodeAnalysis.CSharp.LanguageVersion)Enum.Parse(typeof(CodeAnalysis.CSharp.LanguageVersion), languageVersionAttribute.Value); parseOptions = ((CSharpParseOptions)parseOptions).WithLanguageVersion(languageVersion); } else if (language == LanguageNames.VisualBasic) { var languageVersion = (CodeAnalysis.VisualBasic.LanguageVersion)Enum.Parse(typeof(CodeAnalysis.VisualBasic.LanguageVersion), languageVersionAttribute.Value); parseOptions = ((VisualBasicParseOptions)parseOptions).WithLanguageVersion(languageVersion); } return(parseOptions); }
internal void Load(XElement xSection) { ClearAll(); if (xSection == null) { throw new ArgumentNullException("xSection"); } if (xSection.Name.LocalName != Fb2TextSectionElementName) { throw new ArgumentException("Element of wrong type passed", "xSection"); } XElement xTitle = xSection.Element(xSection.Name.Namespace + TitleItem.Fb2TitleElementName); if (xTitle != null) { Title = new TitleItem(); try { Title.Load(xTitle); } catch (Exception ex) { Debug.WriteLine(string.Format("Failed to load section title : {0}.", ex.Message)); } } IEnumerable <XElement> xEpigraphs = xSection.Elements(xSection.Name.Namespace + EpigraphItem.Fb2EpigraphElementName); foreach (var xEpigraph in xEpigraphs) { EpigraphItem epigraph = new EpigraphItem(); try { epigraph.Load(xEpigraph); _epigraphs.Add(epigraph); } catch (Exception ex) { Debug.WriteLine(string.Format("Failed to load section epigraph : {0}.", ex.Message)); } } XElement xAnnotation = xSection.Element(xSection.Name.Namespace + AnnotationItem.Fb2AnnotationItemName); if (xAnnotation != null) { Annotation = new AnnotationItem(); try { Annotation.Load(xAnnotation); } catch (Exception ex) { Debug.WriteLine(string.Format("Failed to load section annotation : {0}.", ex.Message)); } } IEnumerable <XElement> xElements = xSection.Elements(); foreach (var xElement in xElements) { switch (xElement.Name.LocalName) { case ParagraphItem.Fb2ParagraphElementName: ParagraphItem paragraph = new ParagraphItem(); try { paragraph.Load(xElement); _content.Add(paragraph); } catch (Exception ex) { Debug.WriteLine(string.Format("Failed to load section paragraph : {0}.", ex.Message)); } break; case PoemItem.Fb2PoemElementName: PoemItem poem = new PoemItem(); try { poem.Load(xElement); _content.Add(poem); } catch (Exception ex) { Debug.WriteLine(string.Format("Failed to load section poem : {0}.", ex.Message)); } break; case ImageItem.Fb2ImageElementName: ImageItem image = new ImageItem(); try { image.Load(xElement); AddImage(image); } catch (Exception ex) { Debug.WriteLine(string.Format("Failed to load section image : {0}.", ex.Message)); } break; case SubTitleItem.Fb2SubtitleElementName: SubTitleItem subtitle = new SubTitleItem(); try { subtitle.Load(xElement); _content.Add(subtitle); } catch (Exception ex) { Debug.WriteLine(string.Format("Failed to load section subtitle : {0}.", ex.Message)); } break; case CiteItem.Fb2CiteElementName: CiteItem cite = new CiteItem(); try { cite.Load(xElement); _content.Add(cite); } catch (Exception ex) { Debug.WriteLine(string.Format("Failed to load section citation : {0}.", ex.Message)); } break; case EmptyLineItem.Fb2EmptyLineElementName: EmptyLineItem eline = new EmptyLineItem(); _content.Add(eline); break; case TableItem.Fb2TableElementName: TableItem table = new TableItem(); try { table.Load(xElement); _content.Add(table); } catch (Exception ex) { Debug.WriteLine(string.Format("Failed to load section emptly line : {0}.", ex.Message)); } break; case Fb2TextSectionElementName: // internal <section> read recurive SectionItem section = new SectionItem(); try { section.Load(xElement); AddSection(section); } catch (Exception ex) { Debug.WriteLine(string.Format("Failed to load sub-section : {0}.", ex.Message)); } break; case AnnotationItem.Fb2AnnotationItemName: // already processed break; case TitleItem.Fb2TitleElementName: // already processed break; case EpigraphItem.Fb2EpigraphElementName: // already processed break; default: if (!string.IsNullOrEmpty(xElement.Value)) { ParagraphItem tempParagraph = new ParagraphItem(); try { SimpleText text = new SimpleText { Text = xElement.Value }; tempParagraph.ParagraphData.Add(text); _content.Add(tempParagraph); } catch { // ignored } } Debug.WriteLine("AnnotationItem:Load - invalid element <{0}> encountered in title .", xElement.Name.LocalName); break; } } ID = null; XAttribute xID = xSection.Attribute("id"); if ((xID != null)) { ID = xID.Value; } Lang = null; XAttribute xLang = xSection.Attribute(XNamespace.Xml + "lang"); if ((xLang != null)) { Lang = xLang.Value; } }
public override bool TryGetMember(GetMemberBinder binder, out object result) { string name = binder.Name; if (String.CompareOrdinal(name, "Name") == 0) { result = _element.Name.LocalName; return(true); } else if (String.CompareOrdinal(name, "Parent") == 0) { XElement parent = _element.Parent; if (parent != null) { result = new XmlNode(parent); return(true); } result = null; return(false); } else if (String.CompareOrdinal(name, "Value") == 0) { result = _element.Value; return(true); } else if (String.CompareOrdinal(name, "Nodes") == 0) { result = new XmlNodeList(_element.Elements()); return(true); } else if (String.CompareOrdinal(name, "Xml") == 0) { StringWriter sw = new StringWriter(); _element.Save(sw, SaveOptions.None); result = sw.ToString(); return(true); } else { XAttribute attribute = _element.Attribute(name); if (attribute != null) { result = attribute.Value; return(true); } XElement childNode = _element.Element(name); if (childNode != null) { if (childNode.HasElements == false) { result = childNode.Value; return(true); } result = new XmlNode(childNode); return(true); } } return(base.TryGetMember(binder, out result)); }
private static bool IsXmlTypeAttribute(XAttribute arg) { return(arg.Name.NamespaceName == "http://www.w3.org/2001/XMLSchema-instance" && arg.Name.LocalName == "type"); }
public RuleElement(XElement element) { this.xml = element; this.fullname = Identifier.Get(element.Attribute(XNames.Name).Value + " " + element.Attribute(XNames.Type).Value); this.name = Identifier.Get(element.Attribute(XNames.Name).Value); this.type = Identifier.Get(element.Attribute(XNames.Type).Value); this.id = Identifier.Get(element.Attribute(XNames.InternalID).Value); XAttribute attribute = element.Attribute(XNames.Source); if (attribute != null) { this.source = element.Attribute(XNames.Source).Value; } string description = ""; foreach (XNode node in element.Nodes()) { if (node.NodeType == System.Xml.XmlNodeType.Element) { var subElement = (XElement)node; if (subElement.Name == XNames.Category) { string[] split = subElement.Value.Trim().Split(','); this.category = new Identifier[split.Length]; for (int i = 0; i < split.Length; i++) { category[i] = Identifier.Get(split[i]); } } else if (subElement.Name == XNames.Specific) { string name = subElement.Attribute(XNames.Name).Value; if (SpecificFilter.Contains(name)) { string value = subElement.Value; if (!String.IsNullOrWhiteSpace(value)) { this.specifics[subElement.Attribute(XNames.Name).Value] = value.Trim(); } } } else if (subElement.Name == XNames.Flavor) { this.flavor = subElement.Value; } else if (subElement.Name == XNames.PrintPrereqs) { this.printPrereqs = subElement.Value; } else if (subElement.Name == XNames.Prereqs) { this.preReqs = subElement.Value.Trim().Split(','); } else if (subElement.Name == XNames.Rules) { foreach (XElement ruleElement in subElement.Elements()) { if (ruleElement.Name == XNames.Grant) { this.rules.Add(GrantRule.New(this, ruleElement)); } else if (ruleElement.Name == XNames.TextString) { this.rules.Add(TextStringRule.New(this, ruleElement)); } else if (ruleElement.Name == XNames.StatAdd) { this.rules.Add(StatAddRule.New(this, ruleElement)); } else if (ruleElement.Name == XNames.Select) { this.rules.Add(SelectRule.New(this, ruleElement)); } else if (ruleElement.Name == XNames.Replace) { this.rules.Add(ReplaceRule.New(this, ruleElement)); } else if (ruleElement.Name == XNames.Modify) { this.rules.Add(ModifyRule.New(this, ruleElement)); } else if (ruleElement.Name == XNames.Drop) { this.rules.Add(DropRule.New(this, ruleElement)); } else if (ruleElement.Name == XNames.Suggest) { this.rules.Add(SuggestRule.New(this, ruleElement)); } else if (ruleElement.Name == XNames.StatAlias) { this.rules.Add(StatAliasRule.New(this, ruleElement)); } else { throw new NotSupportedException("Unsupported rule name: " + ruleElement.Name.ToString()); } } } else { throw new NotSupportedException("Unsupported element name: " + subElement.Name.ToString()); } } else if (node.NodeType == System.Xml.XmlNodeType.Text) { description += node.ToString(SaveOptions.DisableFormatting); } } this.description = description.Trim(); }
/// <summary> /// Provides correct IXAttribute depending on XmlTypeCode. /// </summary> /// <param name="attribute">Given XmlSchemaAttribute to process.</param> /// <returns>Coresponding IXAttribute.</returns> private IXAttribute GetXAttribute(XmlSchemaAttribute attribute) { IXAttribute xAttribute; var xmlTypeCode = attribute.AttributeSchemaType.TypeCode; var restriction = attribute.AttributeSchemaType.Content as XmlSchemaSimpleTypeRestriction; //resolve restrictions for simple type (enumeration) if (restriction != null && restriction.Facets.Count > 0) { var xStringRestrictionAttribute = new XEnumerationAttribute<string>(attribute.DefaultValue); foreach (var enumerationFacet in restriction.Facets.OfType<XmlSchemaEnumerationFacet>()) { xStringRestrictionAttribute.Enumeration.Add(enumerationFacet.Value); } //IS ENUMERATION if (xStringRestrictionAttribute.Enumeration.Any()) { xStringRestrictionAttribute.Name = attribute.Name; xStringRestrictionAttribute.Use = (XAttributeUse)attribute.Use; xStringRestrictionAttribute.Value = attribute.DefaultValue; if (xStringRestrictionAttribute.Use == XAttributeUse.None) { xStringRestrictionAttribute.Use = XAttributeUse.Optional;//set default value defined here http://www.w3schools.com/schema/el_attribute.asp } return xStringRestrictionAttribute; } } switch (xmlTypeCode) { case XmlTypeCode.String: xAttribute = new XAttribute<string>(attribute.DefaultValue); ((XAttribute<string>)xAttribute).Value = attribute.DefaultValue; break; case XmlTypeCode.Boolean: xAttribute = new XAttribute<bool>(bool.Parse(attribute.DefaultValue)); if (!string.IsNullOrEmpty(attribute.DefaultValue)) { ((XAttribute<bool>)xAttribute).Value = bool.Parse(attribute.DefaultValue); } break; case XmlTypeCode.Date: var defaultValue = new DateTime(); if (!string.IsNullOrEmpty(attribute.DefaultValue)) { defaultValue = DateTime.Parse(attribute.DefaultValue); } xAttribute = new XAttribute<DateTime>(defaultValue); ((XAttribute<DateTime>)xAttribute).Value = defaultValue; break; case XmlTypeCode.Integer: var defaultValueInteger = 0; if (!string.IsNullOrEmpty(attribute.DefaultValue)) { defaultValueInteger = int.Parse(attribute.DefaultValue); } xAttribute = new XAttribute<int>(defaultValueInteger); ((XAttribute<int>)xAttribute).Value = defaultValueInteger; break; default: throw new ArgumentOutOfRangeException("Unknown XmlTypeCode."); } xAttribute.Name = attribute.Name; xAttribute.Use = (XAttributeUse)attribute.Use; if (xAttribute.Use == XAttributeUse.None) { //set default value defined here http://www.w3schools.com/schema/el_attribute.asp xAttribute.Use = XAttributeUse.Optional; } return xAttribute; }
public void CanUseUpdateBindingForChildren() { //asign var controlManager = new ControlManager(); var xForm = new XForm(); xForm.Root = new XContainer { Name = "BaseContainer" }; var xAttribute1 = new XAttribute<string>(string.Empty) { Name = "StringAttribute1", Value = "StringAttribute", Use = XAttributeUse.Required }; var xAttribute2 = new XAttribute<int>(1) { Name = "StringAttribute2", Use = XAttributeUse.Required }; var xAttribute3 = new XAttribute<bool>(true) { Name = "StringAttribute3", Use = XAttributeUse.Required }; var xAttribute4 = new XAttribute<DateTime>(DateTime.Now) { Name = "StringAttribute4", Use = XAttributeUse.Required }; var xAttribute5 = new XEnumerationAttribute<string>(string.Empty) { Name = "StringAttribute5", Use = XAttributeUse.Required }; var xContainer = new XContainer { Name = "ChildContainer", Value = "ChildContainerValue", ParentContainer = xForm.Root, MaxOccurs = 1234, MinOccurs = 0 }; xContainer.Attributes.Add(xAttribute1); var xElement = new XElement { Name = "Element", Value = "ElementValue" }; xContainer.Elements.Add(xElement); xForm.Root.Attributes.Add(xAttribute1); xForm.Root.Attributes.Add(xAttribute2); xForm.Root.Attributes.Add(xAttribute3); xForm.Root.Attributes.Add(xAttribute4); xForm.Root.Attributes.Add(xAttribute5); xForm.Root.Containers.Add(xContainer); xForm.Root.Elements.Add(xElement); //action controlManager.GetGroupBoxGui(xForm.Root, xForm.Root); controlManager.UpdateBindingForVisibleContainer(xForm.Root); //assert }
public void CreatingXElementsFromNewDev10Types(object t, Type type) { XElement e = new XElement("e1", new XElement("e2"), "text1", new XElement("e3"), t); e.Add(t); e.FirstNode.ReplaceWith(t); XNode n = e.FirstNode.NextNode; n.AddBeforeSelf(t); n.AddAnnotation(t); n.ReplaceWith(t); e.FirstNode.AddAfterSelf(t); e.AddFirst(t); e.Annotation(type); e.Annotations(type); e.RemoveAnnotations(type); e.ReplaceAll(t); e.ReplaceAttributes(t); e.ReplaceNodes(t); e.SetAttributeValue("a", t); e.SetElementValue("e2", t); e.SetValue(t); XAttribute a = new XAttribute("a", t); XStreamingElement se = new XStreamingElement("se", t); se.Add(t); Assert.Throws<ArgumentException>(() => new XDocument(t)); Assert.Throws<ArgumentException>(() => new XDocument(t)); }
public static IXmlSchemaInfo GetSchemaInfo(this XAttribute attribute) { throw new NotImplementedException(); }
// The export method void Export() { // Create a new output file stream doc = new XDocument(); doc.Add(new XElement("Elements")); XElement elements = doc.Element("Elements"); XElement pathPiecesXML = new XElement("PathPieces"); var paths = GameObject.FindGameObjectsWithTag("Path"); foreach (var item in paths) { XElement path = new XElement("Path"); XAttribute attrX = new XAttribute("X", item.transform.position.x); XAttribute attrY = new XAttribute("Y", item.transform.position.y); path.Add(attrX, attrY); pathPiecesXML.Add(path); } pathsCount = paths.Length; elements.Add(pathPiecesXML); XElement waypointsXML = new XElement("Waypoints"); var waypoints = GameObject.FindGameObjectsWithTag("Waypoint"); if (!WaypointsAreValid(waypoints)) { return; } //order by user selected order waypoints = waypoints.OrderBy(x => x.GetComponent<OrderedWaypointForEditor>().Order).ToArray(); foreach (var item in waypoints) { XElement waypoint = new XElement("Waypoint"); XAttribute attrX = new XAttribute("X", item.transform.position.x); XAttribute attrY = new XAttribute("Y", item.transform.position.y); waypoint.Add(attrX, attrY); waypointsXML.Add(waypoint); } waypointsCount = waypoints.Length; elements.Add(waypointsXML); XElement roundsXML = new XElement("Rounds"); foreach (var item in rounds) { XElement round = new XElement("Round"); XAttribute NoOfEnemies = new XAttribute("NoOfEnemies", item.NoOfEnemies); round.Add(NoOfEnemies); roundsXML.Add(round); } elements.Add(roundsXML); XElement towerXML = new XElement("Tower"); var tower = GameObject.FindGameObjectWithTag("Tower"); if(tower == null) { ShowErrorForNull("Tower"); return; } XAttribute towerX = new XAttribute("X", tower.transform.position.x); XAttribute towerY = new XAttribute("Y", tower.transform.position.y); towerXML.Add(towerX, towerY); elements.Add(towerXML); XElement otherStuffXML = new XElement("OtherStuff"); otherStuffXML.Add(new XAttribute("InitialMoney", initialMoney)); otherStuffXML.Add(new XAttribute("MinCarrotSpawnTime", MinCarrotSpawnTime)); otherStuffXML.Add(new XAttribute("MaxCarrotSpawnTime", MaxCarrotSpawnTime)); elements.Add(otherStuffXML); if (!InputIsValid()) return; if (EditorUtility.DisplayDialog("Save confirmation", "Are you sure you want to save level " + filename +"?", "OK", "Cancel")) { doc.Save("Assets/" + filename); EditorUtility.DisplayDialog("Saved", filename + " saved!", "OK"); } else { EditorUtility.DisplayDialog("NOT Saved", filename + " not saved!", "OK"); } }
/// <summary> /// Runs test for valid cases /// </summary> /// <param name="nodeType">XElement/XAttribute</param> /// <param name="name">name to be tested</param> public void RunValidTests(string nodeType, string name) { XDocument xDocument = new XDocument(); XElement element = null; switch (nodeType) { case "XElement": element = new XElement(name, name); xDocument.Add(element); IEnumerable<XNode> nodeList = xDocument.Nodes(); Assert.True(nodeList.Count() == 1, "Failed to create element { " + name + " }"); xDocument.RemoveNodes(); break; case "XAttribute": element = new XElement(name, name); XAttribute attribute = new XAttribute(name, name); element.Add(attribute); xDocument.Add(element); XAttribute x = element.Attribute(name); Assert.Equal(name, x.Name.LocalName); xDocument.RemoveNodes(); break; case "XName": XName xName = XName.Get(name, name); Assert.Equal(name, xName.LocalName); Assert.Equal(name, xName.NamespaceName); Assert.Equal(name, xName.Namespace.NamespaceName); break; default: break; } }
private static bool AttributeToBool(XAttribute attribute, bool defaultValue) { return(attribute == null ? defaultValue : Convert.ToBoolean(attribute.Value)); }
protected override CompletionDataList GetAttributeValueCompletions (IAttributedXObject ob, XAttribute att) { if (ob is XElement && !ob.Name.HasPrefix) { var list = new CompletionDataList (); AddHtmlAttributeValueCompletionData (list, Schema, ob.Name, att.Name); return list; } return null; }
private void BuildLogTable(LogEntry[] entries) { XElement table = new XElement("table"); XElement tableHeader = new XElement("tr"); tableHeader.Add( new XElement("th", " "), new XElement("th", StringResourceSystemFacade.GetString("Composite.Management","ServerLog.LogEntry.DateLabel")), new XElement("th", StringResourceSystemFacade.GetString("Composite.Management","ServerLog.LogEntry.MessageLabel")), new XElement("th", StringResourceSystemFacade.GetString("Composite.Management","ServerLog.LogEntry.TitleLabel")), new XElement("th", StringResourceSystemFacade.GetString("Composite.Management","ServerLog.LogEntry.EventTypeLabel")) //new XElement("th", "URL"), //new XElement("th", "Referer") ); table.Add(tableHeader); foreach (LogEntry logEntry in entries.Reverse()) { TraceEventType eventType; try { eventType = (TraceEventType)Enum.Parse(typeof(TraceEventType), logEntry.Severity); } catch (Exception) { eventType = TraceEventType.Information; } XAttribute color = null; switch (eventType) { case TraceEventType.Information: color = new XAttribute("bgcolor", "lime"); break; case TraceEventType.Verbose: color = new XAttribute("bgcolor", "white"); break; case TraceEventType.Warning: color = new XAttribute("bgcolor", "yellow"); break; case TraceEventType.Error: color = new XAttribute("bgcolor", "orange"); break; case TraceEventType.Critical: color = new XAttribute("bgcolor", "red"); break; default: color = new XAttribute("bgcolor", "pink"); break; } XElement row = new XElement("tr"); row.Add( new XElement("td", " ", color), new XElement("td", string.Format("{0} {1}", logEntry.TimeStamp.ToShortDateString(), logEntry.TimeStamp.ToShortTimeString())), new XElement("td", new XElement("pre", logEntry.Message.Replace("\n", ""))), new XElement("td", logEntry.Title), new XElement("td", logEntry.Severity) //new XElement("td", logEntry.HttpRequestUrl ?? "" + " "), //new XElement("td", logEntry.HttpReferingUrl ?? "" + " ") ); table.Add(row); } LogHolder.Controls.Add(new LiteralControl(table.ToString())); }
public MapGeneratorArgs([NotNull] string fileName) { if (fileName == null) { throw new ArgumentNullException("fileName"); } XDocument doc = XDocument.Load(fileName); XElement root = doc.Root; XAttribute versionTag = root.Attribute("version"); int version = 0; if (versionTag != null && !String.IsNullOrEmpty(versionTag.Value)) { version = Int32.Parse(versionTag.Value); } Theme = (MapGenTheme)Enum.Parse(typeof(MapGenTheme), root.Element("theme").Value, true); Seed = Int32.Parse(root.Element("seed").Value); MapWidth = Int32.Parse(root.Element("dimX").Value); MapLength = Int32.Parse(root.Element("dimY").Value); MapHeight = Int32.Parse(root.Element("dimH").Value); MaxHeight = Int32.Parse(root.Element("maxHeight").Value); MaxDepth = Int32.Parse(root.Element("maxDepth").Value); AddWater = Boolean.Parse(root.Element("addWater").Value); if (root.Element("customWaterLevel") != null) { CustomWaterLevel = Boolean.Parse(root.Element("customWaterLevel").Value); } MatchWaterCoverage = Boolean.Parse(root.Element("matchWaterCoverage").Value); WaterLevel = Int32.Parse(root.Element("waterLevel").Value); WaterCoverage = float.Parse(root.Element("waterCoverage").Value); UseBias = Boolean.Parse(root.Element("useBias").Value); if (root.Element("delayBias") != null) { DelayBias = Boolean.Parse(root.Element("delayBias").Value); } Bias = float.Parse(root.Element("bias").Value); RaisedCorners = Int32.Parse(root.Element("raisedCorners").Value); LoweredCorners = Int32.Parse(root.Element("loweredCorners").Value); MidPoint = Int32.Parse(root.Element("midPoint").Value); if (version == 0) { DetailScale = Int32.Parse(root.Element("minDetailSize").Value); FeatureScale = Int32.Parse(root.Element("maxDetailSize").Value); } else { DetailScale = Int32.Parse(root.Element("detailScale").Value); FeatureScale = Int32.Parse(root.Element("featureScale").Value); } Roughness = float.Parse(root.Element("roughness").Value); LayeredHeightmap = Boolean.Parse(root.Element("layeredHeightmap").Value); MarbledHeightmap = Boolean.Parse(root.Element("marbledHeightmap").Value); InvertHeightmap = Boolean.Parse(root.Element("invertHeightmap").Value); if (root.Element("aboveFuncExponent") != null) { AboveFuncExponent = float.Parse(root.Element("aboveFuncExponent").Value); } if (root.Element("belowFuncExponent") != null) { BelowFuncExponent = float.Parse(root.Element("belowFuncExponent").Value); } AddTrees = Boolean.Parse(root.Element("addTrees").Value); TreeSpacingMin = Int32.Parse(root.Element("treeSpacingMin").Value); TreeSpacingMax = Int32.Parse(root.Element("treeSpacingMax").Value); TreeHeightMin = Int32.Parse(root.Element("treeHeightMin").Value); TreeHeightMax = Int32.Parse(root.Element("treeHeightMax").Value); if (root.Element("addCaves") != null) { AddCaves = Boolean.Parse(root.Element("addCaves").Value); AddCaveLava = Boolean.Parse(root.Element("addCaveLava").Value); AddCaveWater = Boolean.Parse(root.Element("addCaveWater").Value); AddOre = Boolean.Parse(root.Element("addOre").Value); CaveDensity = float.Parse(root.Element("caveDensity").Value); CaveSize = float.Parse(root.Element("caveSize").Value); } if (root.Element("addSnow") != null) { AddSnow = Boolean.Parse(root.Element("addSnow").Value); } if (root.Element("snowAltitude") != null) { SnowAltitude = Int32.Parse(root.Element("snowAltitude").Value); } if (root.Element("snowTransition") != null) { SnowTransition = Int32.Parse(root.Element("snowTransition").Value); } if (root.Element("addCliffs") != null) { AddCliffs = Boolean.Parse(root.Element("addCliffs").Value); } if (root.Element("cliffSmoothing") != null) { CliffSmoothing = Boolean.Parse(root.Element("cliffSmoothing").Value); } if (root.Element("cliffThreshold") != null) { CliffThreshold = float.Parse(root.Element("cliffThreshold").Value); } if (root.Element("addBeaches") != null) { AddBeaches = Boolean.Parse(root.Element("addBeaches").Value); } if (root.Element("beachExtent") != null) { BeachExtent = Int32.Parse(root.Element("beachExtent").Value); } if (root.Element("beachHeight") != null) { BeachHeight = Int32.Parse(root.Element("beachHeight").Value); } if (root.Element("maxHeightVariation") != null) { MaxHeightVariation = Int32.Parse(root.Element("maxHeightVariation").Value); } if (root.Element("maxDepthVariation") != null) { MaxDepthVariation = Int32.Parse(root.Element("maxDepthVariation").Value); } if (root.Element("addGiantTrees") != null) { AddGiantTrees = Boolean.Parse(root.Element("addGiantTrees").Value); } Validate(); }
public void LoadDir() { CorrectAnswersGiven = 0; LettersDone = 0; #region Static Choices Letter.StaticChoices = new Dictionary <string, List <string> >(); string staticChoicesFile = string.Format("{0}/StaticChoices.xml", ActiveDir); if (File.Exists(staticChoicesFile)) { XDocument doc = XDocument.Load(staticChoicesFile); foreach (XElement key in doc.Root.Element("Keys").Elements()) { if (!Letter.StaticChoices.ContainsKey(key.Attribute("romaji").Value)) { List <string> staticChoices = new List <string>(); foreach (XElement staticChoice in key.Elements()) { staticChoices.Add(staticChoice.Value); } Letter.StaticChoices.Add(key.Attribute("romaji").Value, staticChoices); XAttribute alsoReverseAttr = key.Attribute("alsoReverse"); if (alsoReverseAttr != null && bool.Parse(alsoReverseAttr.Value)) { List <string> reverseChoices = new List <string>(staticChoices); reverseChoices.Add(key.Attribute("romaji").Value); foreach (string choice in staticChoices) { if (!Letter.StaticChoices.ContainsKey(choice)) { List <string> temp = new List <string>(reverseChoices); temp.Remove(choice); Letter.StaticChoices.Add(choice, temp); } else { MessageBox.Show( string.Format("\"{0}\" already exists (reversing). Check your StaticChoices.xml!", key.Attribute("romaji").Value), "Warnning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } } else { MessageBox.Show( string.Format("\"{0}\" already exists. Check your StaticChoices.xml!", key.Attribute("romaji").Value), "Warnning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } doc = null; } #endregion string[] images = Directory.GetFiles(LetterDirs[DirIDx], "*.png", SearchOption.TopDirectoryOnly); TotalLetters = images.Count(); AllLetters = new List <Letter>(TotalLetters); AvailableLetters = new List <Letter>(TotalLetters); ProcessedLetters = new List <Letter>(TotalLetters); foreach (string image in images) { AllLetters.Add(new Letter(Path.GetFileNameWithoutExtension(image))); } AvailableLetters = new List <Letter>(AllLetters); RandomizeLetters(); SetChoices(); LanguageDirection = eLanguageDirection.J2E; ThisAnswerIsStillCorrect = true; }
public static void Validate(this XAttribute attribute, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler handler, bool addSchemaInfo) { throw new NotImplementedException(); }
/// <summary> /// Updates the given attribute to the newValue string. /// </summary> /// <param name='attr'> /// The XAttribute instace of the attribute /// </param> /// <param name='newValue'> /// The string of the new value. /// </param> public void UpdateAttribute (XAttribute attr, string newValue) { document.ReplaceText ( attr.Region, String.Format ("{0}=\"{1}\"", attr.Name.Name, newValue) ); }
public static void Main2(string[] args) { DateTime tt0 = DateTime.Now; Console.WriteLine("ConvertProg start"); string filename = @"C:\home\FactographDatabases\PolarDemo\0001.xml"; XElement db = XElement.Load(filename); Console.WriteLine("Load ok. duration={0}", (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now; //Console.WriteLine(db.Elements().Count()); // 176566 // Посмотрим сколько имеется классов Dictionary <string, int> enames = new Dictionary <string, int>(); foreach (XElement element in db.Elements()) { string ename = element.Name.NamespaceName + element.Name.LocalName; int n = -1; if (enames.TryGetValue(ename, out n)) { // Есть в словаре enames[ename] = n + 1; } else { // нет в словаре enames.Add(ename, 1); } } Console.WriteLine(enames.Count); // 23 Console.WriteLine("Load ok. duration={0}", (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now; // Посмотрим сколько в классах элементов foreach (var pair in enames) { Console.WriteLine("{0} {1}", pair.Key, pair.Value); } // Сделаем выборку трех классов (три сосны...) person, photo-doc, reflection. Это почти 100 тыс. объектов, т.е. больше половины от всех. string formats_str = @"<formats> <record type='http://fogid.net/o/person'> <field prop='http://fogid.net/o/name'/> <field prop='http://fogid.net/o/from-date'/> <field prop='http://fogid.net/o/description'/> <field prop='http://fogid.net/o/to-date'/> <field prop='http://fogid.net/o/sex'/> </record> <record type='http://fogid.net/o/photo-doc'> <field prop='http://fogid.net/o/name'/> <field prop='http://fogid.net/o/from-date'/> <field prop='http://fogid.net/o/description'/> </record> <record type='http://fogid.net/o/reflection'> <field prop='http://fogid.net/o/ground'/> <direct prop='http://fogid.net/o/reflected'/> <direct prop='http://fogid.net/o/in-doc'/> </record> </formats>"; XElement formats = XElement.Parse(formats_str); XElement db1 = new XElement("db"); // Поехали... foreach (XElement element in db.Elements()) { string ename = element.Name.NamespaceName + element.Name.LocalName; XElement format = formats.Elements().FirstOrDefault(e => e.Attribute("type").Value == ename); if (format == null) { continue; } string id = element.Attribute("{http://www.w3.org/1999/02/22-rdf-syntax-ns#}about").Value; int c = CodeId(id); XElement el = new XElement(element.Name.LocalName, new XAttribute("id", c)); bool wrong_element = false; foreach (XElement fel in format.Elements()) { string prop = fel.Attribute("prop").Value; string pro = prop.Substring(prop.LastIndexOf('/') + 1); XElement subel = new XElement(pro); if (fel.Name == "field") { XElement f = element.Elements().FirstOrDefault(e => e.Name.NamespaceName + e.Name.LocalName == prop); if (f != null) { subel.Add(f.Value); } } else if (fel.Name == "direct") { XElement d = element.Elements().FirstOrDefault(e => e.Name.NamespaceName + e.Name.LocalName == prop); if (d != null) { XAttribute r = d.Attribute("{http://www.w3.org/1999/02/22-rdf-syntax-ns#}resource"); if (r != null) { subel.Add(new XAttribute("ref", CodeId(r.Value))); } else { wrong_element = true; continue; } } else { wrong_element = true; continue; } } el.Add(subel); } if (!wrong_element) { db1.Add(el); } } db1.Save(@"C:\home\FactographDatabases\PolarDemo\perpho.xml"); foreach (XElement ee in db1.Elements("reflection").Take(100)) { Console.WriteLine(ee.ToString()); } }
protected override CompletionDataList GetAttributeValueCompletions (IAttributedXObject attributedOb, XAttribute att) { XmlElementPath path = GetCurrentPath (); if (path.Elements.Count > 0) { XmlSchemaCompletionData schema = FindSchema (path); if (schema != null) { CompletionData[] completionData = schema.GetAttributeValueCompletionData (path, att.Name.FullName); if (completionData != null) return new CompletionDataList (completionData); } } return null; }
private static EpubSpine ReadSpine(XElement spineNode, EpubVersion epubVersion) { EpubSpine result = new EpubSpine(); foreach (XAttribute spineNodeAttribute in spineNode.Attributes()) { string attributeValue = spineNodeAttribute.Value; switch (spineNodeAttribute.GetLowerCaseLocalName()) { case "id": result.Id = attributeValue; break; case "page-progression-direction": result.PageProgressionDirection = PageProgressionDirectionParser.Parse(attributeValue); break; case "toc": result.Toc = attributeValue; break; } } if (epubVersion == EpubVersion.EPUB_2 && String.IsNullOrWhiteSpace(result.Toc)) { #if STRICTEPUB throw new Exception("Incorrect EPUB spine: TOC is missing"); #endif } foreach (XElement spineItemNode in spineNode.Elements()) { if (spineItemNode.CompareNameTo("itemref")) { EpubSpineItemRef spineItemRef = new EpubSpineItemRef(); foreach (XAttribute spineItemNodeAttribute in spineItemNode.Attributes()) { string attributeValue = spineItemNodeAttribute.Value; switch (spineItemNodeAttribute.GetLowerCaseLocalName()) { case "id": spineItemRef.Id = attributeValue; break; case "idref": spineItemRef.IdRef = attributeValue; break; case "properties": spineItemRef.Properties = SpinePropertyParser.ParsePropertyList(attributeValue); break; } } if (String.IsNullOrWhiteSpace(spineItemRef.IdRef)) { throw new Exception("Incorrect EPUB spine: item ID ref is missing"); } XAttribute linearAttribute = spineItemNode.Attribute("linear"); spineItemRef.IsLinear = linearAttribute == null || !linearAttribute.CompareValueTo("no"); result.Add(spineItemRef); } } return(result); }
/// <summary> /// Runs test for InValid cases /// </summary> /// <param name="nodeType">XElement/XAttribute</param> /// <param name="name">name to be tested</param> public void RunInValidTests(string nodeType, string name) { XDocument xDocument = new XDocument(); XElement element = null; try { switch (nodeType) { case "XElement": element = new XElement(name, name); xDocument.Add(element); IEnumerable<XNode> nodeList = xDocument.Nodes(); break; case "XAttribute": element = new XElement(name, name); XAttribute attribute = new XAttribute(name, name); element.Add(attribute); xDocument.Add(element); XAttribute x = element.Attribute(name); break; case "XName": XName xName = XName.Get(name, name); break; default: break; } } catch (XmlException) { return; } catch (ArgumentException) { return; } Assert.True(false, "Expected exception not thrown"); }
/// <summary> /// Ensures individual transactions are valid, discards transactions that aren't valid. /// </summary> private void processDetails() { XDocument xdoc = new XDocument(); xdoc = XDocument.Load(inputFileName); XElement root = xdoc.Element("student_update"); //Grab attributes within the root element XAttribute date = root.Attribute("date"); XAttribute program = root.Attribute("program"); XAttribute checksum = root.Attribute("checksum"); //Values within attributes DateTime dateValue = DateTime.Parse(date.Value); string programAckValue = program.Value; string checksumValue = checksum.Value; long checksumParsed = long.Parse(checksumValue); //Get all transactions in the document IEnumerable <XElement> transactions = from results in xdoc.Descendants() where results.Name == "transaction" select results; //Getting all of the nodes where the node count is equal to seven IEnumerable <XElement> nodeCount = from results in transactions where results.Nodes().Count() == 7 select results; //Compare the transactions to the node count queries processErrors(transactions, nodeCount, "Node count is not equal to seven\r\n"); //Query to get all programs that are equal to the root's value for program -----> Failing at this point IEnumerable <XElement> programs = from results in nodeCount where results.Element("program").Value == programAckValue select results; //Comparing programs to the node count query processErrors(nodeCount, programs, "Program listed is not equal to the root value.\r\n"); //Querying to get the types where the values are numeric IEnumerable <XElement> types = from results in programs where Numeric.isNumeric(results.Element("type").Value, System.Globalization.NumberStyles.Number) where results.Element("type").Value == "1" || results.Element("type").Value == "2" select results; //Comparing types vs program queries processErrors(programs, types, "Type is not numeric\r\n"); //If grade is *, or numeric (and is within the valid grade range) IEnumerable <XElement> grades = from results in types where Numeric.isNumeric(results.Element("grade").Value, System.Globalization.NumberStyles.Float) && double.Parse(results.Element("grade").Value) >= 0 && double.Parse(results.Element("grade").Value) <= 100 || results.Element("grade").Value == "*" select results; //Comapring grades vs. type queries processErrors(types, grades, "Value for grade isn't valid\r\n"); //Getting student numbers from db IQueryable <long> dbStudentNumbers = from results in db.Students select results.StudentNumber; //Querying for student numbers IEnumerable <XElement> studentNumbers = from results in grades where dbStudentNumbers.Contains(long.Parse(results.Element("student_no").Value)) select results; //Comparing student number to grades query processErrors(grades, studentNumbers, "Student Number does not exist within database\r\n"); //Query DB to get course numbers IQueryable <string> dbCourseNumbers = from results in db.Courses select results.CourseNumber; //Query to get course numbers: type 2 then grading, type 1 for registration IEnumerable <XElement> courseNumbers = from results in studentNumbers where dbCourseNumbers.Contains(results.Element("course_no").Value) && results.Element("type").Value == "1" || results.Element("type").Value == "2" && results.Element("course_no").Value == "*" select results; //Comparing courseNumbers query to student numbers query processErrors(studentNumbers, courseNumbers, "Invalid course number\r\n"); //Querying db for registration numbers IQueryable <long> dbRegistrationNumbers = from results in db.Registrations select results.RegistrationNumber; //Querying for registration numbers IEnumerable <XElement> registrationNumbers = from results in courseNumbers where results.Element("type").Value == "2" && dbRegistrationNumbers.Contains(long.Parse(results.Element("registration_no").Value)) || results.Element("type").Value == "1" && results.Element("registration_no").Value == "*" select results; //Comparing registration numbers to course numbers processErrors(courseNumbers, registrationNumbers, "Registration number doesn't exist\r\n"); //Pass the error free result set to processTransactions method processTransactions(registrationNumbers); }
private void BuildLogTable(LogEntry[] entries) { XElement table = new XElement("table"); XElement tableHeader = new XElement("tr"); tableHeader.Add( new XElement("th", " "), new XElement("th", StringResourceSystemFacade.GetString("Composite.Management","ServerLog.LogEntry.DateLabel")), new XElement("th", StringResourceSystemFacade.GetString("Composite.Management","ServerLog.LogEntry.MessageLabel")), new XElement("th", StringResourceSystemFacade.GetString("Composite.Management","ServerLog.LogEntry.TitleLabel")), new XElement("th", StringResourceSystemFacade.GetString("Composite.Management","ServerLog.LogEntry.EventTypeLabel")) ); table.Add(tableHeader); foreach (LogEntry logEntry in entries.Reverse()) { TraceEventType eventType; try { eventType = (TraceEventType)Enum.Parse(typeof(TraceEventType), logEntry.Severity); } catch (Exception) { eventType = TraceEventType.Information; } var colors = new [] { new Tuple<TraceEventType, string>(TraceEventType.Information, "lime"), new Tuple<TraceEventType, string>(TraceEventType.Verbose, "white"), new Tuple<TraceEventType, string>(TraceEventType.Warning, "yellow"), new Tuple<TraceEventType, string>(TraceEventType.Error, "orange"), new Tuple<TraceEventType, string>(TraceEventType.Critical, "red") }; string colorName = colors.Where(c => c.Item1 == eventType).Select(c => c.Item2).FirstOrDefault() ?? "orange"; XAttribute color = new XAttribute("bgcolor", colorName); XElement row = new XElement("tr"); row.Add( new XElement("td", color, " "), new XElement("td", logEntry.TimeStamp.ToString(View_DateTimeFormat)), new XElement("td", new XElement("pre", EncodeXml10InvalidCharacters(logEntry.Message.Replace("\n", "")))), new XElement("td", EncodeXml10InvalidCharacters(logEntry.Title)), new XElement("td", logEntry.Severity) ); table.Add(row); } LogHolder.Controls.Add(new LiteralControl(table.ToString())); }
/// <summary> /// Processes the root element's attributes to ensure a valid file /// </summary> private void processHeaders() { //Loading the xdocument object with the xml file XDocument xdoc = new XDocument(); xdoc = XDocument.Load(inputFileName); //Pull root element XElement root = xdoc.Element("student_update"); //Grab attributes within the root element XAttribute date = root.Attribute("date"); XAttribute program = root.Attribute("program"); XAttribute checksum = root.Attribute("checksum"); //Values within attributes DateTime dateValue = DateTime.Parse(date.Value); string programAckValue = program.Value; string checksumValue = checksum.Value; long checksumParsed = long.Parse(checksumValue); //Counting the attributes in the root element int rootAttributeCount = root.Attributes().Count(); //if the root attribute count is 3 then proceed. if (rootAttributeCount != 3) { throw new Exception("incorrect number of attributes in root element.\r\n"); } DateTime today = DateTime.Today; bool dateComparison = dateValue.Equals(today); if (dateComparison == false) { throw new Exception("date is not valid.\r\n"); } string programValidation = (from results in db.Programs where results.ProgramAcronym == programAckValue select results.ProgramAcronym).SingleOrDefault(); if (programValidation == null) { throw new Exception("program acronym does not exist.\r\n"); } //Grab all child elements of the root to validate checksum IEnumerable <XElement> children = from results in root.Descendants() where results.Name == "student_no" select results; long total = 0; foreach (XElement x in children) { //Grab each student number within each student_no element, parse and add string studentNumber = x.Value; long studentNumberParsed = long.Parse(studentNumber); total += studentNumberParsed; } if (total != checksumParsed) { throw new Exception("checksum is not valid\r\n"); } }
protected virtual CompletionDataList GetAttributeValueCompletions (IAttributedXObject attributedOb, XAttribute att) { return null; }
public static MSBuildResolveResult Resolve( XmlParser parser, IReadonlyTextDocument document, MSBuildDocument context) { int offset = parser.Position; //clones and connects nodes to their parents parser = parser.GetTreeParser(); var nodePath = parser.Nodes.ToList(); nodePath.Reverse(); //capture incomplete names, attributes and element values int i = offset; if (parser.CurrentState is XmlRootState && parser.Nodes.Peek() is XElement unclosedEl) { while (i < document.Length && InRootOrClosingTagState() && !unclosedEl.IsClosed) { parser.Push(document.GetCharAt(i++)); } } else { while (i < document.Length && InNameOrAttributeState()) { parser.Push(document.GetCharAt(i++)); } } //if nodes are incomplete, they won't get connected //HACK: the only way to reconnect them is reflection if (nodePath.Count > 1) { for (int idx = 1; idx < nodePath.Count; idx++) { var node = nodePath [idx]; if (node.Parent == null) { var parent = nodePath [idx - 1]; ParentProp.SetValue(node, parent); } } } //need to look up element by walking how the path, since at each level, if the parent has special children, //then that gives us information to identify the type of its children MSBuildLanguageElement languageElement = null; MSBuildLanguageAttribute languageAttribute = null; XElement el = null; XAttribute att = null; foreach (var node in nodePath) { if (node is XAttribute xatt && xatt.Name.Prefix == null) { att = xatt; languageAttribute = languageElement?.GetAttribute(att.Name.Name); break; } //if children of parent is known to be arbitrary data, don't go into it if (languageElement != null && languageElement.ValueKind == MSBuildValueKind.Data) { break; } //code completion is forgiving, all we care about best guess resolve for deepest child if (node is XElement xel && xel.Name.Prefix == null) { el = xel; languageElement = MSBuildLanguageElement.Get(el.Name.Name, languageElement); if (languageElement != null) { continue; } } languageElement = null; } if (languageElement == null) { return(null); } var rr = new MSBuildResolveResult { LanguageElement = languageElement, LanguageAttribute = languageAttribute, XElement = el, XAttribute = att }; var rv = new MSBuildResolveVisitor(offset, rr); rv.Run(el, languageElement, document.FileName, document, context); return(rr); bool InNameOrAttributeState() => parser.CurrentState is XmlNameState || parser.CurrentState is XmlAttributeState || parser.CurrentState is XmlAttributeValueState; bool InRootOrClosingTagState() => parser.CurrentState is XmlRootState || parser.CurrentState is XmlNameState || parser.CurrentState is XmlClosingTagState; }
public void DifferentNamespacesSameNameAttributes() { XAttribute a = new XAttribute("{NamespaceOne}Name", "a"), b = new XAttribute("{NamespaceTwo}Name", "b"); Assert.NotSame(a.Name.Namespace, b.Name.Namespace); Assert.NotSame(a.Name, b.Name); }
protected override void VisitValueExpression( XElement element, XAttribute attribute, MSBuildLanguageElement resolvedElement, MSBuildLanguageAttribute resolvedAttribute, ValueInfo info, MSBuildValueKind kind, ExpressionNode node) { switch (node.Find(offset)) { case ExpressionItemName ei: rr.ReferenceKind = MSBuildReferenceKind.Item; rr.ReferenceOffset = ei.Offset; rr.ReferenceLength = ei.Name.Length; rr.Reference = ei.Name; break; case ExpressionPropertyName propName: rr.ReferenceKind = MSBuildReferenceKind.Property; rr.ReferenceOffset = propName.Offset; rr.Reference = propName.Name; rr.ReferenceLength = propName.Length; break; case ExpressionMetadata em: if (em.ItemName == null || offset >= em.MetadataNameOffset) { rr.ReferenceKind = MSBuildReferenceKind.Metadata; rr.ReferenceOffset = em.MetadataNameOffset; rr.Reference = (em.GetItemName(), em.MetadataName); rr.ReferenceLength = em.MetadataName.Length; } else { rr.ReferenceKind = MSBuildReferenceKind.Item; rr.ReferenceOffset = em.ItemNameOffset; rr.Reference = em.ItemName; rr.ReferenceLength = em.ItemName.Length; } break; case ExpressionFunctionName name: rr.ReferenceOffset = name.Offset; rr.ReferenceLength = name.Name.Length; if (name.Parent is ExpressionItemNode item) { rr.ReferenceKind = MSBuildReferenceKind.ItemFunction; rr.Reference = name.Name; } else if (name.Parent is ExpressionPropertyFunctionInvocation prop) { if (prop.Target is ExpressionClassReference classRef) { rr.ReferenceKind = MSBuildReferenceKind.StaticPropertyFunction; rr.Reference = (classRef.Name, name.Name); } else { var type = FunctionCompletion.ResolveType(prop.Target); rr.ReferenceKind = MSBuildReferenceKind.PropertyFunction; rr.Reference = (type, name.Name); } } break; case ExpressionClassReference cr: if (!string.IsNullOrEmpty(cr.Name)) { if (cr.Parent is ExpressionArgumentList) { rr.ReferenceKind = MSBuildReferenceKind.Enum; } else if (cr.Parent is ExpressionPropertyFunctionInvocation) { rr.ReferenceKind = MSBuildReferenceKind.ClassName; } else { break; } rr.ReferenceOffset = cr.Offset; rr.Reference = cr.Name; rr.ReferenceLength = cr.Length; } break; case ExpressionText lit: kind = kind.GetScalarType(); if (lit.IsPure) { VisitPureLiteral(element, info, kind, lit); if (kind == MSBuildValueKind.TaskOutputParameterName) { rr.ReferenceKind = MSBuildReferenceKind.TaskParameter; rr.ReferenceOffset = lit.Offset; rr.ReferenceLength = lit.Value.Length; rr.Reference = (element.ParentElement().Name.Name, lit.Value); break; } } switch (kind) { case MSBuildValueKind.File: case MSBuildValueKind.FileOrFolder: case MSBuildValueKind.ProjectFile: case MSBuildValueKind.TaskAssemblyFile: var pathNode = lit.Parent as Expression ?? (ExpressionNode)lit; var path = MSBuildNavigation.GetPathFromNode(pathNode, (MSBuildRootDocument)Document); if (path != null) { rr.ReferenceKind = MSBuildReferenceKind.FileOrFolder; rr.ReferenceOffset = path.Offset; rr.ReferenceLength = path.Length; rr.Reference = path.Paths; } break; } break; } }
protected override CompletionDataList GetAttributeValueCompletions (IAttributedXObject attributedOb, XAttribute att) { var path = GetElementPath (); if (path.Elements.Count > 0) { var schema = FindSchema (path); if (schema != null) return schema.GetAttributeValueCompletionData (path, att.Name.FullName); } return null; }
/// <summary> /// Gets the object from XML attribute. /// </summary> /// <remarks> /// Note that this method can cause exceptions. The caller will handle them. /// </remarks> /// <param name="attribute">The attribute.</param> /// <param name="memberValue">The property data.</param> /// <returns>Object or <c>null</c>.</returns> private object GetObjectFromXmlAttribute(XAttribute attribute, MemberValue memberValue) { var value = attribute.Value; return(StringToObjectHelper.ToRightType(memberValue.Type, value)); }