static void Main() { // Create the data source by using a collection initializer. // The Student class was defined previously in this topic. List<Student> students = new List<Student>() { new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores = new List<int>{97, 92, 81, 60}}, new Student {First="Claire", Last="O’Donnell", ID=112, Scores = new List<int>{75, 84, 91, 39}}, new Student {First="Sven", Last="Mortensen", ID=113, Scores = new List<int>{88, 94, 65, 91}}, }; // Create the query. var studentsToXML = new XElement("Root", from student in students let x = String.Format("{0},{1},{2},{3}", student.Scores[0], student.Scores[1], student.Scores[2], student.Scores[3]) select new XElement("student", new XElement("First", student.First), new XElement("Last", student.Last), new XElement("Scores", x) ) // end "student" ); // end "Root" // Execute the query. Console.WriteLine(studentsToXML); // Keep the console open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); }
public override bool ShowConfiguration(XElement config) { var dialog = new LiveSplitConfigurationDialog(config); if (dialog.ShowDialog().GetValueOrDefault(false)) { if (config.Parent.GetInt("cx") == 0 || config.Parent.GetInt("cy") == 0) { try { using (var layoutStream = System.IO.File.OpenRead(config.GetString("layoutpath"))) { var xmlDoc = new System.Xml.XmlDocument(); xmlDoc.Load(layoutStream); var parent = xmlDoc["Layout"]; var width = parent["VerticalWidth"]; config.Parent.SetInt("cx", int.Parse(width.InnerText)); var height = parent["VerticalHeight"]; config.Parent.SetInt("cy", int.Parse(height.InnerText)); //TODO Will break with horizontal } } catch (Exception ex) { Log.Error(ex); } } return true; } return false; }
void AddMember (XElement element) { string id; if (element.IsRunatServer () && !string.IsNullOrEmpty (id = element.GetId ())) { if (Members.ContainsKey (id)) { Errors.Add (new Error ( ErrorType.Error, GettextCatalog.GetString ("Tag ID must be unique within the document: '{0}'.", id), element.Region ) ); } else { string controlType = element.Attributes.GetValue (new XName ("type"), true); IType type = docRefMan.GetType (element.Name.Prefix, element.Name.Name, controlType); if (type == null) { Errors.Add ( new Error ( ErrorType.Error, GettextCatalog.GetString ("The tag type '{0}{1}{2}' has not been registered.", element.Name.Prefix, element.Name.HasPrefix ? string.Empty : ":", element.Name.Name), element.Region ) ); } else Members [id] = new CodeBehindMember (id, type, element.Region.Begin); } } foreach (XElement child in element.Nodes.OfType<XElement> ()) AddMember (child); }
public void Reload(XElement element) { JavaScriptSerializer serializer = new JavaScriptSerializer(); BrowserSourceSettings = AbstractSettings.DeepClone(BrowserSettings.Instance.SourceSettings); BrowserInstanceSettings = AbstractSettings.DeepClone(BrowserSettings.Instance.InstanceSettings); String instanceSettingsString = element.GetString("instanceSettings"); String sourceSettingsString = element.GetString("sourceSettings"); if (sourceSettingsString != null && sourceSettingsString.Count() > 0) { try { BrowserSourceSettings = serializer.Deserialize<BrowserSourceSettings>(sourceSettingsString); } catch (ArgumentException e) { API.Instance.Log("Failed to deserialized source settings and forced to recreate; {0}", e.Message); } } if (instanceSettingsString != null && instanceSettingsString.Count() > 0) { BrowserInstanceSettings.MergeWith(serializer.Deserialize<BrowserInstanceSettings>(instanceSettingsString)); } }
/// <summary> /// Converts a given <see cref="T:XElement"/> into an <see cref="T:Account"/>. /// </summary> /// <param name="element">The <see cref="T:XElement"/> to convert.</param> /// <returns>The newly created <see cref="T:Account"/>.</returns> public Account FromXElement(XElement element) { Account account = AccountFactory.Create(element.Name.LocalName); foreach (XElement childNode in element.Nodes()) { switch (childNode.Name.LocalName) { case "AccountID": account.AccountID = new Guid(childNode.Value); break; case "CreatedByUsername": account.CreatedByUsername = childNode.Value; break; case "CreatedDate": account.CreatedDate = DateTime.Parse(childNode.Value); break; case "Description": account.Description = childNode.Value; break; case "Name": account.Name = childNode.Value; break; case "UpdatedByUsername": account.UpdatedByUsername = childNode.Value; break; case "UpdatedDate": account.UpdatedDate = DateTime.Parse(childNode.Value); break; case "ChangeSetHistory": ChangeSetHistoryXElementAdapter adapter = new ChangeSetHistoryXElementAdapter(); account.ChangeSetHistory = adapter.FromXElement(childNode); break; } } return account; }
public void SameNamespaceDifferentNamesElements() { var a = new XElement("{NameSpace}NameOne"); var b = new XElement("{NameSpace}NameTwo"); Assert.Same(a.Name.Namespace, b.Name.Namespace); Assert.NotSame(a.Name, b.Name); }
public void DefaultNamespaceDifferentNameElements() { var a = new XElement("NameOne"); var b = new XElement("NameTwo"); Assert.Same(a.Name.Namespace, b.Name.Namespace); Assert.NotSame(a.Name, b.Name); }
/// <summary> /// Converts a given <see cref="T:XElement"/> into a <see cref="T:ChangeSetHistory"/>. /// </summary> /// <param name="element">The <see cref="T:XElement"/> to convert.</param> /// <returns>The newly created <see cref="T:ChangeSetHistory"/>.</returns> public ChangeSetHistory FromXElement(XElement element) { ChangeSetHistory history = new ChangeSetHistory(); foreach (XElement changeSetElement in element.Nodes()) { ChangeSet changeSet = new ChangeSet(); // Get the change set details foreach (XElement changeSetElementChild in changeSetElement.Nodes()) { if (changeSetElementChild.Name.LocalName == "Applied") { changeSet.Applied = DateTime.Parse(changeSetElementChild.Value); } else if (changeSetElementChild.Name.LocalName == "Username") { changeSet.Username = changeSetElementChild.Value; } else if (changeSetElementChild.Name.LocalName == "Change") { Change change = new Change(); foreach (XElement changeElement in changeSetElementChild.Nodes()) { if (changeElement.Name.LocalName == "PropertyName") { change.PropertyName = changeElement.Value; } else if (changeElement.Name.LocalName == "OldValue") { change.OldValue = changeElement.Value; } else if (changeElement.Name.LocalName == "NewValue") { change.NewValue = changeElement.Value; } } changeSet.Changes.Add(change); } } history.Append(changeSet); } return history; }
/// <summary> /// Inserts an attribute to an XElement in the source code editor. /// </summary> /// <param name='el'> /// the tag's XElement instance /// </param> /// <param name='key'> /// Key. /// </param> /// <param name='value'> /// Value. /// </param> public void InsertAttribute (XElement el, string key, string value) { int line = el.Region.EndLine; int column = 1; // a preceding space or nothing string preambula = String.Empty; // a space or nothing after the last quote string ending = String.Empty; if (el.IsSelfClosing) { column = el.Region.EndColumn - 2; // "/>" // a space before the /> of the tag ending = " "; } else { column = el.Region.EndColumn -1; // ">" // no need for a space in the end of an openning tag } // check if a space is needed infront of the attribute // or the method should write at the first column of a new line if (column > 1) { string whatsBeforeUs = document.GetTextFromEditor (line, column - 1, line, column); if (!String.IsNullOrWhiteSpace (whatsBeforeUs)) preambula = " "; } // finally, insert the result document.InsertText ( new TextLocation (line, column), String.Format ("{0}{1}=\"{2}\"{3}", preambula, key, value, ending) ); }
private static void Main() { helper.ConsoleMio.Setup(); helper.ConsoleMio.PrintHeading("Extract Contact Information"); string selctedFile = SelectFileToOpen(); string saveLocation = SelectSaveLocation(); var contactInfo = new XElement("person"); using (var inputStream = new StreamReader(selctedFile)) { string currentLine; while ((currentLine = inputStream.ReadLine()) != null) { string[] args = currentLine.Split(' '); string tag = args[0]; string content = string.Join(" ", args.Skip(1).ToArray()); contactInfo.Add(new XElement(tag, content)); } } contactInfo.Save(saveLocation); helper.ConsoleMio.PrintColorText("Completed\n ", ConsoleColor.Green); helper.ConsoleMio.Restart(Main); }
public DccObsImageSource(XElement config) { ExecuteCmd("LiveViewWnd_Show"); Thread.Sleep(1000); ExecuteCmd("All_Minimize"); this.config = config; UpdateSettings(); }
public BrowserSource(XElement configElement) { this.configElement = configElement; this.browserConfig = new BrowserConfig(); this.textureMap = new Dictionary<IntPtr, Texture>(); UpdateSettings(); }
public void NoneNamespaceSameNameElements() { var a = new XElement(XNamespace.None + "Name"); var b = new XElement(XNamespace.None + "Name"); Assert.Same(XNamespace.None, b.Name.Namespace); Assert.Same(a.Name.Namespace, b.Name.Namespace); Assert.Same(a.Name, b.Name); }
public void XmlNamespaceDifferentNameElements() { var a = new XElement(XNamespace.Xml + "NameOne"); var b = new XElement(XNamespace.Xml + "NameTwo"); Assert.Same(XNamespace.Xml, b.Name.Namespace); Assert.Same(a.Name.Namespace, b.Name.Namespace); Assert.NotSame(a.Name, b.Name); }
public void XmlnsNamespaceSameNameElements() { var a = new XElement(XNamespace.Xmlns + "Name"); var b = new XElement(XNamespace.Xmlns + "Name"); Assert.Same(XNamespace.Xmlns, a.Name.Namespace); Assert.Same(a.Name.Namespace, b.Name.Namespace); Assert.Same(a.Name, b.Name); }
public MumbleOverlayConfigurationDialog(XElement config) { InitializeComponent(); this.config = config; widthText.Text = config.GetInt("width").ToString(); heightText.Text = config.GetInt("height").ToString(); }
public static void SetCustomProperties(object obj, IEnumerable<PropertyInfo> properties, XElement data) { foreach (var xmlProperty in data.Descendants("CustomProperty")) { string propertyName = xmlProperty.Attribute("Name").Value; PropertyInfo propertyInfo = properties.Where(info => info.Name == propertyName).First(); } }
public XmlMultipleClosingTagCompletionData (XElement finalEl, XElement[] intermediateElements) { name = finalEl.Name.FullName; description = GettextCatalog.GetString ("Closing tag for '{0}', also closing all intermediate tags", name); name = string.Format ("/{0}>...", name); this.intEls = intermediateElements; this.finalEl = finalEl; }
/// <summary> /// Determines whether this XElement instance contains a runat="server" attribute. /// </summary> /// <returns> /// <c>true</c> if this instance contains a runat="server" attribute; otherwise, <c>false</c>. /// </returns> /// <param name='el'> /// The XElement instace to be checked /// </param> public static bool IsRunAtServer (XElement el) { XName runat = new XName ("runat"); foreach (XAttribute a in el.Attributes) { if ((a.Name.ToLower () == runat) && (a.Value.ToLower () == "server")) return true; } return false; }
public static void NodesBeforeSelfBeforeAndAfter() { XText aText = new XText("a"), bText = new XText("b"); XElement a = new XElement("A", aText, bText); IEnumerable<XNode> nodes = bText.NodesBeforeSelf(); Assert.Equal(1, nodes.Count()); aText.Remove(); Assert.Equal(0, nodes.Count()); }
public override bool ShowConfiguration(XElement data) { //StarboardConfigurationDialog dialog = new StarboardConfigurationDialog(data); //return dialog.ShowDialog().GetValueOrDefault(false); //MainWindowView m = new MainWindowView(); //return m.ShowDialog().GetValueOrDefault(); return true; }
public void CData(string value1, string value2, bool checkHashCode) { XCData t1 = new XCData(value1); XCData t2 = new XCData(value2); VerifyComparison(checkHashCode, t1, t2); XElement e2 = new XElement("p2p", t2); e2.Add(t1); VerifyComparison(checkHashCode, t1, t2); }
public static void ElementsAfterSelfWithXNameBeforeAndAfter() { XText aText = new XText("a"), bText = new XText("b"); XElement a = new XElement("A", aText), b = new XElement("B", bText); a.Add(b); IEnumerable<XElement> nodes = aText.ElementsAfterSelf("B"); Assert.Equal(1, nodes.Count()); b.ReplaceWith(a); Assert.Equal(0, nodes.Count()); }
public static void AncestorsWithXNameBeforeAndAfter() { XText aText = new XText("a"), bText = new XText("b"); XElement a = new XElement("A", aText), b = new XElement("B", bText); a.Add(b); IEnumerable<XElement> nodes = bText.Ancestors("B"); Assert.Equal(1, nodes.Count()); bText.Remove(); a.Add(bText); Assert.Equal(0, nodes.Count()); }
public void Comment(string value1, string value2, bool checkHashCode) { XComment c1 = new XComment(value1); XComment c2 = new XComment(value2); VerifyComparison(checkHashCode, c1, c2); XDocument doc = new XDocument(c1); XElement e2 = new XElement("p2p", c2); VerifyComparison(checkHashCode, c1, c2); }
public OutlineNode (XElement el) { Name = el.Name.FullName; string id = el.GetId (); if (!string.IsNullOrEmpty (id)) Name = "<" + Name + "#" + id + ">"; else Name = "<" + Name + ">"; Location = el.Region; }
public SampleConfigurationDialog(XElement config) { InitializeComponent(); this.config = config; String file = config.GetString("file"); if (File.Exists(file)) { LoadImage(new Uri(config.GetString("file"))); } }
public void ProcessingInstruction(string target1, string data1, string target2, string data2, bool checkHashCode) { var p1 = new XProcessingInstruction(target1, data1); var p2 = new XProcessingInstruction(target2, data2); VerifyComparison(checkHashCode, p1, p2); XDocument doc = new XDocument(p1); XElement e2 = new XElement("p2p", p2); VerifyComparison(checkHashCode, p1, p2); }
public ConfigDialog(XElement dataElement) { InitializeComponent(); this.dataElement = dataElement; config = new BrowserConfig(); config.Reload(dataElement); cssEditor = new TextEditor { FontFamily = new FontFamily("Consolas"), SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("CSS"), ShowLineNumbers = true, Options = { ConvertTabsToSpaces = true, IndentationSize = 2 } }; templateEditor = new TextEditor { FontFamily = new FontFamily("Consolas"), SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("HTML"), ShowLineNumbers = true, Options = { ConvertTabsToSpaces = true, IndentationSize = 2 } }; advancedPropertiesCheckBox.IsChecked = config.BrowserSourceSettings.IsShowingAdvancedProperties; SetTabVisibility(advancedTab, config.BrowserSourceSettings.IsShowingAdvancedProperties); SetTabVisibility(templateTab, config.BrowserSourceSettings.IsApplyingTemplate); url.Text = config.BrowserSourceSettings.Url; cssEditor.Text = config.BrowserSourceSettings.CSS; templateEditor.Text = config.BrowserSourceSettings.Template; widthText.Text = config.BrowserSourceSettings.Width.ToString(); heightText.Text = config.BrowserSourceSettings.Height.ToString(); opacitySlider.Value = config.BrowserSourceSettings.Opacity; fpsTextBox.Text = config.BrowserSourceSettings.Fps.ToString(); applyTemplateCheckBox.IsChecked = config.BrowserSourceSettings.IsApplyingTemplate; instanceSettings.SelectedObject = config.BrowserInstanceSettings; cssGrid.Children.Add(cssEditor); templateGrid.Children.Add(templateEditor); }
public XTextChangedCache(XText newText) { // 一致しない場合はとりあえず放置. if (newText.Parent == currentParent) { this.OldValue = currentOldValue; this.Parent = newText.Parent; this.NewValue = newText.Value; currentParent = null; currentOldValue = null; } }
public ImprovementPrerequisite(XElement definition) : base(definition) { Count = (int)definition.Attribute("Count"); }
public abstract string GetDescription(XElement e);
public override void Modified(XElement source, XElement target) { }
public override void SetContext(XElement current) { }
public override void Compare(IEnumerable <XElement> source, IEnumerable <XElement> target) { removed.Clear(); foreach (var s in source) { SetContext(s); Source = s; var t = target.SingleOrDefault(Find); if (t == null) { // not in target, it was removed removed.Add(s); } else { // possibly modified if (Equals(s, t)) { t.Remove(); continue; } // still in target so will be part of Added removed.Add(s); Modified(s, t); } } // delayed, that way we show "Modified", "Added" and then "Removed" bool r = false; foreach (var item in removed) { SetContext(item); if (!r) { BeforeRemoving(); r = true; } Removed(item); } if (r) { AfterRemoving(); } // remaining == newly added in target bool a = false; foreach (var item in target) { SetContext(item); if (!a) { BeforeAdding(); a = true; } Added(item); } if (a) { AfterAdding(); } }
public object Parse(XElement field, Type t) { return ParseDate(field.Value); }
public static DatabaseOptions LoadOptions(XElement parentNode) { var result = new DatabaseOptions(); result.Load(parentNode); return result; }
protected abstract void InternalSaveToElement(XElement xmlElement);
public FilterItemText(XElement xmlElement, string attributeName) : base(xmlElement, attributeName) { }
/// <summary> /// Gets the text of an XElement. /// </summary> /// <param name="node">Element to get text.</param> /// <returns>The element's text.</returns> internal static string GetInnerText(XElement node) { var text = node.Nodes().Where(n => XmlNodeType.Text == n.NodeType || XmlNodeType.CDATA == n.NodeType).Cast <XText>().FirstOrDefault(); return(text?.Value); }
private void ReadArrayData(XElement element, out bool[] array) { this.ReadPrimitiveArrayData(element, out array, s => XmlConvert.ToBoolean(s)); }
private void ReadArrayData(XElement element, out byte[] array) { array = Convert.FromBase64String(element.Value); }
private void ReadArrayData(XElement element, out sbyte[] array) { this.ReadPrimitiveArrayData(element, out array, s => (sbyte)XmlConvert.ToInt16(s)); }
private static IList <MetadataReference> CreateCommonReferences(TestWorkspace workspace, XElement element) { var references = new List <MetadataReference>(); var net45 = element.Attribute(CommonReferencesNet45AttributeName); if (net45 != null && ((bool?)net45).HasValue && ((bool?)net45).Value) { references = new List <MetadataReference> { TestBase.MscorlibRef_v4_0_30316_17626, TestBase.SystemRef_v4_0_30319_17929, TestBase.SystemCoreRef_v4_0_30319_17929 }; if (GetLanguage(workspace, element) == LanguageNames.VisualBasic) { references.Add(TestBase.MsvbRef); references.Add(TestBase.SystemXmlRef); references.Add(TestBase.SystemXmlLinqRef); } } var commonReferencesAttribute = element.Attribute(CommonReferencesAttributeName); if (commonReferencesAttribute != null && ((bool?)commonReferencesAttribute).HasValue && ((bool?)commonReferencesAttribute).Value) { references = new List <MetadataReference> { TestBase.MscorlibRef_v4_0_30316_17626, TestBase.SystemRef_v4_0_30319_17929, TestBase.SystemCoreRef_v4_0_30319_17929 }; if (GetLanguage(workspace, element) == LanguageNames.VisualBasic) { references.Add(TestBase.MsvbRef_v4_0_30319_17929); references.Add(TestBase.SystemXmlRef); references.Add(TestBase.SystemXmlLinqRef); } } var winRT = element.Attribute(CommonReferencesWinRTAttributeName); if (winRT != null && ((bool?)winRT).HasValue && ((bool?)winRT).Value) { references = new List <MetadataReference>(TestBase.WinRtRefs.Length); references.AddRange(TestBase.WinRtRefs); if (GetLanguage(workspace, element) == LanguageNames.VisualBasic) { references.Add(TestBase.MsvbRef_v4_0_30319_17929); references.Add(TestBase.SystemXmlRef); references.Add(TestBase.SystemXmlLinqRef); } } var portable = element.Attribute(CommonReferencesPortableAttributeName); if (portable != null && ((bool?)portable).HasValue && ((bool?)portable).Value) { references = new List <MetadataReference>(TestBase.PortableRefsMinimal.Length); references.AddRange(TestBase.PortableRefsMinimal); } var systemRuntimeFacade = element.Attribute(CommonReferenceFacadeSystemRuntimeAttributeName); if (systemRuntimeFacade != null && ((bool?)systemRuntimeFacade).HasValue && ((bool?)systemRuntimeFacade).Value) { references.Add(TestBase.FacadeSystemRuntimeRef); } return(references); }
public SonarTransducer(Item item, XElement element) : base(item, element) { IsActive = true; }
protected abstract void InternalLoadFromElement(XElement xmlElement);
public void Save(XElement xmlElement) { AddAttrValue(xmlElement, "FilterBy" + AttributeName, this.Enabled.ToString()); InternalSaveToElement(xmlElement); }
protected override void InternalSaveToElement(XElement xmlElement) { base.InternalSaveToElement(xmlElement); AddAttrValue(xmlElement, "IncludeItemsFromColorHighlight" + AttributeName, this.IncludeItemsFromColorHighlight.ToString()); }
/// <summary> /// Deserializes an XML node to an instance of Category /// </summary> internal static Category XmlDeserialize(string payload) { // deserialize to xml and use the overload to do the work return(XmlDeserialize(XElement.Parse(payload))); }
protected override void InternalLoadFromElement(XElement xmlElement) { base.InternalLoadFromElement(xmlElement); this.IncludeItemsFromColorHighlight = GetAttrValue<bool>(s => Boolean.Parse(s), xmlElement, "IncludeItemsFromColorHighlight" + AttributeName, false); }
public virtual bool Find(XElement e) { return(e.GetAttribute("name") == Source.GetAttribute("name")); }
public FilterItemMessage(XElement xmlElement, string attributeName) : base(xmlElement, attributeName) { }
public override void Removed(XElement source) { Indent().WriteLine("\t{0}", GetDescription(source)); }
public FilterItem(XElement xmlElement, string attributeName) { this.AttributeName = attributeName; this.Enabled = GetAttrValue<bool>(s => Boolean.Parse(s), xmlElement, "FilterBy" + attributeName, EnabledByDefault); this.InternalLoadFromElement(xmlElement); }
public override void Added(XElement target) { Indent().WriteLine("\t{0}", GetDescription(target)); }
protected override void InternalSaveToElement(XElement xmlElement) { XElement xmlListElement = AddList<string>(item => new XElement("Item", item), xmlElement, AttributeName, this.TextLines.ToList()); AddAttrValue(xmlListElement, "EditorToShow", ((int)EditorToShow).ToString()); AddAttrValue(xmlListElement, "UseRegex", this.UseRegex.ToString()); }
public async Task <XDocument> GenerateResults(MutationTestingSession session, bool includeDetailedTestResults, bool includeCodeDifferenceListings, ProgressCounter progress, CancellationToken token) { _log.Info("Generating session results to file."); int multiplier = 1; if (includeDetailedTestResults) { multiplier++; } if (includeCodeDifferenceListings) { multiplier++; } List <Mutant> mutants = session.MutantsGrouped.Cast <CheckedNode>() .SelectManyRecursive(n => n.Children ?? new NotifyingCollection <CheckedNode>(), leafsOnly: true).OfType <Mutant>().ToList(); List <Mutant> mutantsWithErrors = mutants.Where(m => m.State == MutantResultState.Error).ToList(); List <Mutant> testedMutants = mutants.Where(m => m.MutantTestSession.IsComplete).ToList(); List <Mutant> live = testedMutants.Where(m => m.State == MutantResultState.Live).ToList(); progress.Initialize(mutants.Count * multiplier); var mutantsNode = new XElement("Mutants", new XAttribute("Total", mutants.Count), new XAttribute("Live", live.Count), new XAttribute("Killed", testedMutants.Count - live.Count), new XAttribute("Untested", mutants.Count - testedMutants.Count), new XAttribute("WithError", mutantsWithErrors.Count), new XAttribute("AverageCreationTimeMiliseconds", testedMutants .AverageOrZero(mut => mut.CreationTimeMilis)), new XAttribute("AverageTestingTimeMiliseconds", testedMutants .AverageOrZero(mut => mut.MutantTestSession.TestingTimeMiliseconds)), from assemblyNode in session.MutantsGrouped select new XElement("Assembly", new XAttribute("Name", assemblyNode.Name), from type in assemblyNode.Children.SelectManyRecursive( n => n.Children ?? new NotifyingCollection <CheckedNode>()) .OfType <TypeNode>() select new XElement("Type", new XAttribute("Name", type.Name), new XAttribute("Namespace", type.Namespace), from method in type.Children.Cast <MethodNode>()//TODO: what if nested type? select new XElement("Method", new XAttribute("Name", method.Name), from mutant in method.Children.SelectManyRecursive( n => n.Children ?? new NotifyingCollection <CheckedNode>()).OfType <Mutant>() select new XElement("Mutant", new XAttribute("Id", mutant.Id), new XAttribute("Description", mutant.Description), new XAttribute("State", mutant.State), new XAttribute("IsEquivalent", mutant.IsEquivalent), new XAttribute("CreationTimeMiliseconds", mutant.CreationTimeMilis), new XAttribute("TestingTimeMiliseconds", mutant.MutantTestSession.TestingTimeMiliseconds), new XAttribute("TestingEndRelativeSeconds", (mutant.MutantTestSession.TestingEnd - _sessionController.SessionStartTime).TotalSeconds), new XElement("ErrorInfo", new XElement("Description", mutant.MutantTestSession.ErrorDescription), new XElement("ExceptionMessage", mutant.MutantTestSession.ErrorMessage) ).InArrayIf(mutant.State == MutantResultState.Error) ) ) ) ) ); var optionalElements = new List <XElement>(); if (includeCodeDifferenceListings) { var res = await CreateCodeDifferenceListings(mutants, progress, token); optionalElements.Add(res); } if (includeDetailedTestResults) { var res = await Task.Run(() => CreateDetailedTestingResults(mutants, progress, token)); optionalElements.Add(res); } return (new XDocument( new XElement("MutationTestingSession", new XAttribute("SessionCreationWindowShowTime", _choices.SessionCreationWindowShowTime), new XAttribute("SessionStartTime", _sessionController.SessionStartTime), new XAttribute("SessionEndTime", _sessionController.SessionEndTime), new XAttribute("SessionRunTimeSeconds", (_sessionController.SessionEndTime - _sessionController.SessionStartTime).TotalSeconds), new XAttribute("MutationScore", ((int)(session.MutationScore * 100)).ToString()), mutantsNode, optionalElements))); }
/// <summary> /// Fetches the value of "param" tags from xml documentation with in valus of "body" /// and populates operation's request body. /// </summary> /// <param name="operation">The operation to be updated.</param> /// <param name="element">The xml element representing an operation in the annotation xml.</param> /// <param name="settings">The operation filter settings.</param> /// <remarks> /// Care should be taken to not overwrite the existing value in Operation if already present. /// This guarantees the predictable behavior that the first tag in the XML will be respected. /// It also guarantees that common annotations in the config file do not overwrite the /// annotations in the main documentation. /// </remarks> public void Apply(OpenApiOperation operation, XElement element, OperationFilterSettings settings) { var bodyElements = element.Elements() .Where( p => p.Name == KnownXmlStrings.Param && p.Attribute(KnownXmlStrings.In)?.Value == KnownXmlStrings.Body) .ToList(); SchemaReferenceRegistry schemaReferenceRegistry = settings.ReferenceRegistryManager.SchemaReferenceRegistry; foreach (var bodyElement in bodyElements) { var name = bodyElement.Attribute(KnownXmlStrings.Name)?.Value.Trim(); var mediaType = bodyElement.Attribute(KnownXmlStrings.Type)?.Value ?? "application/json"; var childNodes = bodyElement.DescendantNodes().ToList(); var description = string.Empty; var lastNode = childNodes.LastOrDefault(); if (lastNode != null && lastNode.NodeType == XmlNodeType.Text) { description = lastNode.ToString().Trim().RemoveBlankLines(); } var allListedTypes = bodyElement.GetListedTypes(); if (!allListedTypes.Any()) { throw new InvalidRequestBodyException( string.Format(SpecificationGenerationMessages.MissingSeeCrefTag, name)); } var type = settings.TypeFetcher.LoadTypeFromCrefValues(allListedTypes); var schema = schemaReferenceRegistry.FindOrAddReference(type); var examples = bodyElement.ToOpenApiExamples(settings.TypeFetcher); if (examples.Count > 0) { var firstExample = examples.First().Value?.Value; if (firstExample != null) { // In case a schema is a reference, find that schmea object in schema registry // and update the example. if (schema.Reference != null) { var key = schemaReferenceRegistry.GetKey(type); if (schemaReferenceRegistry.References.ContainsKey(key)) { settings.ReferenceRegistryManager.SchemaReferenceRegistry.References[key].Example = firstExample; } } else { schema.Example = firstExample; } } } if (operation.RequestBody == null) { operation.RequestBody = new OpenApiRequestBody { Description = description.RemoveBlankLines(), Content = { [mediaType] = new OpenApiMediaType { Schema = schema } }, Required = true }; } else { if (string.IsNullOrWhiteSpace(operation.RequestBody.Description)) { operation.RequestBody.Description = description.RemoveBlankLines(); } if (!operation.RequestBody.Content.ContainsKey(mediaType)) { operation.RequestBody.Content[mediaType] = new OpenApiMediaType { Schema = schema }; } else { if (!operation.RequestBody.Content[mediaType].Schema.AnyOf.Any()) { var existingSchema = operation.RequestBody.Content[mediaType].Schema; var newSchema = new OpenApiSchema(); newSchema.AnyOf.Add(existingSchema); operation.RequestBody.Content[mediaType].Schema = newSchema; } operation.RequestBody.Content[mediaType].Schema.AnyOf.Add(schema); } } if (examples.Count > 0) { if (operation.RequestBody.Content[mediaType].Examples.Any()) { examples.CopyInto(operation.RequestBody.Content[mediaType].Examples); } else { operation.RequestBody.Content[mediaType].Examples = examples; } } } }
private static IList <AnalyzerReference> CreateAnalyzerList(TestWorkspace workspace, XElement projectElement) { var analyzers = new List <AnalyzerReference>(); foreach (var analyzer in projectElement.Elements(AnalyzerElementName)) { analyzers.Add( new AnalyzerImageReference( ImmutableArray <DiagnosticAnalyzer> .Empty, display: (string)analyzer.Attribute(AnalyzerDisplayAttributeName), fullPath: (string)analyzer.Attribute(AnalyzerFullPathAttributeName))); } return(analyzers); }
private void ReadArrayData(XElement element, out ushort[] array) { this.ReadPrimitiveArrayData(element, out array, s => XmlConvert.ToUInt16(s)); }