/// <summary> /// Processes the record. /// </summary> protected override void ProcessRecord() { this.WriteVerbose("Formatting log"); using (var xmlReader = new StringReader(this.Log)) { var xpath = new XPathDocument(xmlReader); using (var writer = new StringWriter()) { var transform = new XslCompiledTransform(); Func<string, string> selector = file => !Path.IsPathRooted(file) ? Path.Combine(Environment.CurrentDirectory, file) : file; foreach (var fileToLoad in this.FormatFile.Select(selector)) { this.WriteVerbose("Loading format file " + fileToLoad); using (var stream = File.OpenRead(fileToLoad)) { using (var reader = XmlReader.Create(stream)) { transform.Load(reader); transform.Transform(xpath, null, writer); } } } this.WriteObject(writer.GetStringBuilder().ToString(), false); } } }
public string Visit(string text) { text = text.Trim(); var lines = new List<string>(); using (var stringReader = new StringReader(text)) { string line; while ((line = stringReader.ReadLine()) != null) { line = line.Trim(); lines.Add(line); } } lines.Sort(); var stringBuilder = new StringBuilder(); foreach (var line in lines) { stringBuilder.AppendLine(line); } return stringBuilder.ToString(); }
private void button1_Click(object sender, RoutedEventArgs e) { ++equationsCount; string xamlTextBox = XamlWriter.Save(t1); StringReader stringReader = new StringReader(xamlTextBox); XmlReader xmlReader = XmlReader.Create(stringReader); TextBox newTextBox = (TextBox)XamlReader.Load(xmlReader); newTextBox.Name = "t" + equationsCount.ToString(); newTextBox.Text = ""; newTextBox.LostFocus += textBox_LostFocus; newTextBox.Margin = new Thickness(0, 29*(equationsCount-1) + 4, 6, 0); grid2.Children.Add(newTextBox); string xamlLabel = XamlWriter.Save(label2); stringReader = new StringReader(xamlLabel); xmlReader = XmlReader.Create(stringReader); Label newLabel = (Label)XamlReader.Load(xmlReader); newLabel.Name = "label" + (equationsCount*2).ToString(); newLabel.Content = equationsCount.ToString() +":"; newLabel.Margin = new Thickness(6, 29 * (equationsCount-1) + 4, 0, 0); grid2.Children.Add(newLabel); varForEq.Add(new List<string>()); }
public void Go() { var outputFile = Helpers.IO.GetClassOutputPath(this); var fixedHtml = FixBrokenServerControlMarkup(HTML); using (FileStream stream = new FileStream( outputFile, FileMode.Create, FileAccess.Write)) { using (var document = new Document()) { PdfWriter writer = PdfWriter.GetInstance( document, stream ); document.Open(); using (var xmlSnippet = new StringReader(fixedHtml)) { XMLWorkerHelper.GetInstance().ParseXHtml( writer, document, xmlSnippet ); } } } }
public static TriviaMessage Deserialize(string dataReceived) { /* bool correctEnding = (dataReceived.EndsWith("</TriviaMessage>")); if (!correctEnding) { throw new InvalidOperationException("Deserialization will fail..."); } */ XmlSerializer serializer = new XmlSerializer(typeof(TriviaMessage)); StringReader reader = new StringReader(dataReceived); TriviaMessage message = null; try { message = (TriviaMessage)(serializer.Deserialize(reader)); } catch (Exception ex) { throw new InvalidOperationException(string.Format("Failed to deserialize this data received '{0}'", dataReceived), ex); } reader.Close(); return message; }
public static object DeserializeAudioTracks(string tracksString) { XmlSerializer xmlDeSerializer = new XmlSerializer(typeof(List<BackgroundTrackItem>)); StringReader textReader = new StringReader(tracksString); return xmlDeSerializer.Deserialize(textReader) as List<BackgroundTrackItem>; }
static LispReader() { _macros['"'] = new StringReader(); _macros[';'] = new CommentReader(); _macros['\''] = new WrappingReader(QUOTE); _macros['@'] = new WrappingReader(DEREF);//new DerefReader(); _macros['^'] = new WrappingReader(META); _macros['`'] = new SyntaxQuoteReader(); _macros['~'] = new UnquoteReader(); _macros['('] = new ListReader(); _macros[')'] = new UnmatchedDelimiterReader(); _macros['['] = new VectorReader(); _macros[']'] = new UnmatchedDelimiterReader(); _macros['{'] = new MapReader(); _macros['}'] = new UnmatchedDelimiterReader(); //// macros['|'] = new ArgVectorReader(); _macros['\\'] = new CharacterReader(); _macros['%'] = new ArgReader(); _macros['#'] = new DispatchReader(); _dispatchMacros['^'] = new MetaReader(); _dispatchMacros['\''] = new VarReader(); _dispatchMacros['"'] = new RegexReader(); _dispatchMacros['('] = new FnReader(); _dispatchMacros['{'] = new SetReader(); _dispatchMacros['='] = new EvalReader(); _dispatchMacros['!'] = new CommentReader(); _dispatchMacros['<'] = new UnreadableReader(); _dispatchMacros['_'] = new DiscardReader(); }
public static Table Parse(IRestResponse response) { Table table = new Table(); StringReader reader = new StringReader(response.Content); string readLine = reader.ReadLine(); if (readLine != null) { string[] collection = readLine.Split(Separator); foreach (string column in collection) { table.Columns.Add(column.TrimStart('"').TrimEnd('"')); } } string line = reader.ReadLine(); while (!string.IsNullOrEmpty(line)) { Row row = new Row(line); table.Rows.Add(row); line = reader.ReadLine(); } return table; }
public UnityEditor.EditorBuildSettingsScene[] GetPreviousScenesToRestore() { string text = null; if (Application.isEditor) { text = GetTextFromTempFile(previousScenes); } if(text != null) { var serializer = new System.Xml.Serialization.XmlSerializer(typeof(UnityEditor.EditorBuildSettingsScene[])); using(var textReader = new StringReader(text)) { try { return (UnityEditor.EditorBuildSettingsScene[] )serializer.Deserialize(textReader); } catch (System.Xml.XmlException e) { Debug.Log (e); return null; } } } return null; }
public static BackgroundTrackItem DeserializeObjectAudioTrack(this string s) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(BackgroundTrackItem)); StringReader textReader = new StringReader(s); return xmlSerializer.Deserialize(textReader) as BackgroundTrackItem; }
public virtual void TestStemming() { TextReader reader = new StringReader("questões"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); stream = TokenFilterFactory("PortugueseMinimalStem").Create(stream); AssertTokenStreamContents(stream, new string[] { "questão" }); }
public virtual void TestStemming() { TextReader reader = new StringReader("chevaux"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); stream = TokenFilterFactory("FrenchMinimalStem").Create(stream); AssertTokenStreamContents(stream, new string[] { "cheval" }); }
public void TestConnectorSerialization() { var obj = new TwoInOneOutExpression(); var tw = new StringWriter(); using (var xw = XmlWriter.Create(tw)) { xw.WriteStartElement("Node"); obj.Serialize(xw); xw.WriteEndElement(); } var sr = new StringReader(tw.ToString()); using (var wr = XmlReader.Create(sr)) { wr.ReadToFollowing("Node"); var result = new TwoInOneOutExpression(); result.Deserialize(wr); Assert.AreEqual(obj.Id, result.Id); Assert.AreEqual(obj.Connector1In.Id, result.Connector1In.Id); Assert.AreEqual(obj.Connector2In.Id, result.Connector2In.Id); Assert.AreEqual(obj.ConnectorOut.Id, result.ConnectorOut.Id); } }
public PipelineContinuation StripResponseElement(ICommunicationContext context) { var passedApiUrl = (string)context.PipelineData["ApiUrl"]; if (string.IsNullOrEmpty(passedApiUrl)) return PipelineContinuation.Continue; var xmlDocument = (XmlDocument)context.PipelineData["ApiXmlResponse"]; // read and remove response header to get result var responseElement = xmlDocument.SelectSingleNode("/response"); var responseStatusAttribute = responseElement.Attributes["status"]; var innerXml = responseElement.InnerXml; var stringReader = new StringReader(innerXml); // get the type Type generatedType = responseStatusAttribute.InnerText == "ok" ? _typeGenerator.GenerateType(passedApiUrl) : typeof(Error); var serializer = new XmlSerializer(generatedType); object deserialized = serializer.Deserialize(stringReader); if (responseStatusAttribute.InnerText == "ok") context.OperationResult = new OperationResult.OK(deserialized); else context.OperationResult = new OperationResult.BadRequest { ResponseResource = deserialized }; return PipelineContinuation.Continue; }
public Document Parse(string commonMark) { using (var reader = new StringReader(commonMark)) { return Parse(reader); } }
public static string Filter(string stack) { if (stack == null) { return null; } StringWriter writer = new StringWriter(); StringReader reader = new StringReader(stack); try { string str2; while ((str2 = reader.ReadLine()) != null) { if (!FilterLine(str2)) { writer.WriteLine(str2.Trim()); } } } catch (Exception) { return stack; } return writer.ToString(); }
public void GenerateCode(FileProjectItem item, CustomToolContext context) { context.RunAsync( ()=> { string fileName = item.FileName; var projectNode = item.Project; SpecFlowProject specFlowProject = CreateSpecFlowProjectFrom(projectNode); var specFlowGenerator = new SpecFlowGenerator(specFlowProject); string outputFile = context.GetOutputFileName(item, ".feature"); var specFlowFeatureFile = specFlowProject.GetOrCreateFeatureFile(fileName); var fileContents = File.ReadAllText(fileName); string outputFileContents; using(var reader = new StringReader(fileContents)) { using (var writer = new StringWriter(new StringBuilder())) { specFlowGenerator.GenerateTestFile(specFlowFeatureFile, projectNode.LanguageProperties.CodeDomProvider, reader, writer); outputFileContents = writer.ToString(); } } File.WriteAllText(outputFile, outputFileContents); WorkbenchSingleton.SafeThreadCall( () => context.EnsureOutputFileIsInProject(item, outputFile)); }); }
public void testFutureBaseRequest() { StringReader rdr = new StringReader("0030-delta-2011-03-13T05-38-00Z"); DeltaRequestResultKind result = DeltaRequestHandler.handleDeltaRequest(deltaDir, new MasterNodeList<int>(), new MasterNodeList<int>(), new ToStringNodeValueExporter<int>(),rdr, new MemoryStream()); Assert.AreEqual(DeltaRequestResultKind.Mismatch, result); }
private async void UpdateContributors() { try { var vms = await Task.Run(async () => { var hc = new HttpClient(); var str = await hc.GetStringAsync(App.ContributorsUrl); using (var sr = new StringReader(str)) { var xml = XDocument.Load(sr); return xml.Root .Descendants("contributor") .Where( e => e.Attribute("visible") == null || e.Attribute("visible").Value.ToLower() != "false") .Select(ContributorsViewModel.FromXml) .ToArray(); } }); await DispatcherHelper.UIDispatcher.InvokeAsync( () => { this.Contributors.Clear(); this.Contributors.Add(new ContributorsViewModel("thanks to:", null)); vms.OrderBy(v => v.ScreenName ?? "~" + v.Name) .ForEach(this.Contributors.Add); }); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } }
/// <summary> /// 读取指定节点的值 /// </summary> /// <param name="XmlPathNode">节点的XPATH</param> /// <returns>返回一个DataView</returns> public DataSet GetData(string XmlPathNode) { DataSet ds = new DataSet(); StringReader read = new StringReader(objXmlDoc.SelectSingleNode(XmlPathNode).OuterXml); ds.ReadXml(read); return ds; }
public static IList<string> ParseInstalledPluginsFile(string filePath) { //read and parse the file if (!File.Exists(filePath)) return new List<string>(); var text = File.ReadAllText(filePath); if (String.IsNullOrEmpty(text)) return new List<string>(); //Old way of file reading. This leads to unexpected behavior when a user's FTP program transfers these files as ASCII (\r\n becomes \n). //var lines = text.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); var lines = new List<string>(); using (var reader = new StringReader(text)) { string str; while ((str = reader.ReadLine()) != null) { if (String.IsNullOrWhiteSpace(str)) continue; lines.Add(str.Trim()); } } return lines; }
public void Activate(string[] args) { bool verbose = false; if (args.Length > 0) { foreach (string arg in args) { if (arg.ToLower() == "/verbose") verbose = true; } } try { runtime = new Runtime(); Environment globalEnvironment = new Environment(); foreach (string line in LSharpCode) { if (verbose) Console.Write(line + " --> "); System.IO.StringReader reader = new System.IO.StringReader(line); object output = Runtime.EvalString(line, globalEnvironment); Console.WriteLine(Printer.WriteToString(output)); } } catch (Exception e) { Console.WriteLine(e.ToString()); } System.Console.WriteLine("Press any key to Continue..."); System.Console.ReadKey(true); }
public static IEnumerable<string> ReadLines(this string content) { string line; using (var sr = new StringReader(content)) while ((line = sr.ReadLine()) != null) yield return line; }
public List<SequenceContract> ParseFastaFile(string fastaContent) { StringReader sr = new StringReader(fastaContent); List<SequenceContract> sequences = new List<SequenceContract>(); SequenceList bioSeqList = null; using (ReaderBase reader = new BioFastaReader()) { bioSeqList = reader.Read(sr); } foreach (Sequence seq in bioSeqList) sequences.Add (new SequenceContract() { Name = seq.Annotations("SequenceName").AnnotationValue as string, AlphabetName = seq.Alphabet.Name, Characters = seq.Letters() } ); return sequences; }
public static object Deserialize(string xmlContent, string serializerType) { object returnValue = null; SerializerTypes serializerTypeValue; Type instanceType; GetSerializerDetails(serializerType, out serializerTypeValue, out instanceType); if (serializerTypeValue == SerializerTypes.XmlSerializer) { StringReader sww = new StringReader(xmlContent); XmlReader reader = XmlReader.Create(sww); System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(instanceType); returnValue = serializer.Deserialize(reader); } else if (serializerTypeValue == SerializerTypes.XmlObjectSerializer) { XmlObjectSerializer serializer = new XmlObjectSerializer(); returnValue = serializer.Deserialize(xmlContent, true); } else { if (instanceType == typeof(string)) { returnValue = xmlContent; } else { var method = instanceType.GetMethod("Parse", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); returnValue = method.Invoke(null, new object[] { xmlContent }); } } return returnValue; }
public virtual void TestPositionIncrements() { Reader reader = new StringReader("foo foobar super-duper-trooper"); TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); stream = TokenFilterFactory("Length", LengthFilterFactory.MIN_KEY, "4", LengthFilterFactory.MAX_KEY, "10").Create(stream); AssertTokenStreamContents(stream, new string[] { "foobar" }, new int[] { 2 }); }
protected void btnPDF_Click(object sender, ImageClickEventArgs e) { Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=UserDetails.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); var sw = new StringWriter(); var hw = new HtmlTextWriter(sw); gvdetails.AllowPaging = false; gvdetails.DataBind(); gvdetails.RenderControl(hw); gvdetails.HeaderRow.Style.Add("width", "15%"); gvdetails.HeaderRow.Style.Add("font-size", "10px"); gvdetails.Style.Add("text-decoration", "none"); gvdetails.Style.Add("font-family", "Arial, Helvetica, sans-serif;"); gvdetails.Style.Add("font-size", "8px"); var sr = new StringReader(sw.ToString()); var pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f); var htmlparser = new HTMLWorker(pdfDoc); PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); Response.Write(pdfDoc); Response.End(); }
private List<double> significance_level; //Уровнь значимости //Загружает таблицу критических значений private CriticalPirsonCriterion() { try { using (var sr = new StringReader(Resources.PirsonCritical)) { int k = 1; //Степень свободы string line; //Текущая строка table = new List<Dictionary<double, double>>(); //Парсим первую строку с уровнями значимости line = sr.ReadLine(); significance_level = get_significance_levle(line); //Читаем оставшиеся строки и заполняем таблицу while ((line = sr.ReadLine()) != null) table.Add(get_line_values(line, significance_level)); } } catch(FormatException exp) { throw new Exception("ОШИБКА ФАЙЛА КРИТИЧЕСКИХ ТОЧЕК: значение в файле не является числом"); } catch(IOException exp) { throw new Exception("ОШИБКА ФАЙЛА КРИТИЧЕСКИХ ТОЧЕК: не удается открыть файл"); } catch(Exception exp) { throw exp; } }
private static void CheckSplits(string testString, string expectedSplits) { StringReader r = new StringReader(testString); var filter = SnowballAndWordSplittingAnalyzer.GetStandardFilterSet(r); int expectToFindThisMany = expectedSplits.Split().Length; var expectedSplitWords = new HashSet<string>(); foreach (var term in expectedSplits.Split()) expectedSplitWords.Add(term.ToLower()); var notExpected = new HashSet<string>(); Token token = filter.Next(); HashSet<string> foundSplits = new HashSet<string>() ; while (token!=null && !String.IsNullOrEmpty(token.ToString())) { Debug.WriteLine(token.Term()); int before = expectedSplitWords.Count; expectedSplitWords.Remove(token.Term()); int after = expectedSplitWords.Count; if (before == after) notExpected.Add(token.Term()); foundSplits.Add(token.Term()); token = filter.Next(); } Assert.AreEqual(0, expectedSplitWords.Count); Assert.AreEqual(foundSplits.Count, expectToFindThisMany, string.Join(", ", notExpected)); }
public void Run_should_populate_StartTime_and_EndTime_and_TotalRunTime() { // Arrange var beforeStart = DateTime.UtcNow; var config = new Config(); var testCaseReader = new TestCaseReaderMock(); var stringReader = new StringReader(""); var response = new HttpResponse(); response.ResponseTime = TimeSpan.FromSeconds(5); HttpClientMock httpClient = new HttpClientMock(response); IResultWriter resultWriter = new ResultWriterStub(); var runner = new TestSessionRunner(config, httpClient, resultWriter); var caseCollection = CreateCaseCollection(new[] { new Case() { Url = "foo1" }, }); // Act TestCaseSession session = runner.Run(caseCollection); // Assert Assert.That(session.StartTime, Is.GreaterThanOrEqualTo(beforeStart)); Assert.That(session.EndTime, Is.GreaterThanOrEqualTo(session.StartTime)); Assert.That(session.TotalRunTime, Is.EqualTo(session.EndTime - session.StartTime)); }
public new static ListMonadicFunctionsBoolType111 Deserialize(string input) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(input); return((ListMonadicFunctionsBoolType111)(Serializer.Deserialize(XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } }
public static retourBevestigingBevestiging Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return((retourBevestigingBevestiging)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } }
public static TemplateAdminTypeDigitalSignatureSignaturePropertiesX_CertificateAuthority Deserialize(string input) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(input); return((TemplateAdminTypeDigitalSignatureSignaturePropertiesX_CertificateAuthority)(Serializer.Deserialize(XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } }
public static artikelEigenschapArtikelEigenschapGegevens Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return((artikelEigenschapArtikelEigenschapGegevens)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } }
public static IEnumerable <string> SplitToLines(this string input) { if (input == null) { yield break; } using (System.IO.StringReader reader = new System.IO.StringReader(input)) { string line; while ((line = reader.ReadLine()) != null) { yield return(line); } } }
public static NumTrigNumType111TrigRadians Deserialize(string input) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(input); return((NumTrigNumType111TrigRadians)(Serializer.Deserialize(XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } }
public new static ContactType Deserialize(string input) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(input); return((ContactType)(Serializer.Deserialize(XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } }
public new static TemplateAdminTypeDigitalSignature Deserialize(string input) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(input); return((TemplateAdminTypeDigitalSignature)(Serializer.Deserialize(XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } }
public new static negativeInteger_Stype Deserialize(string input) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(input); return((negativeInteger_Stype)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } }
public new static ListFilterListType000 Deserialize(string input) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(input); return((ListFilterListType000)(Serializer.Deserialize(XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } }
public static TRetEnviNFeInfRec Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return((TRetEnviNFeInfRec)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } }
public static BalanzaCtas Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return((BalanzaCtas)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } }
public new static SimpleSdcRetrieveFormPackageTypeXMLPackageReportDesignTemplate Deserialize(string input) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(input); return((SimpleSdcRetrieveFormPackageTypeXMLPackageReportDesignTemplate)(Serializer.Deserialize(XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } }
private void LoadPlayerValues() { XmlSerializer serializer = new XmlSerializer(typeof(PlayerValues)); string text = PlayerPrefs.GetString("player values"); if (text.Length == 0) { playerValues = new PlayerValues(); } else { using (var reader = new System.IO.StringReader(text)) { playerValues = serializer.Deserialize(reader) as PlayerValues; } } }
public new static SDCPackageList Deserialize(string input) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(input); return((SDCPackageList)(Serializer.Deserialize(XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } }
public new static IsBetweenTypeMin_Expression Deserialize(string input) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(input); return((IsBetweenTypeMin_Expression)(Serializer.Deserialize(XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } }
public new static NominaReceptorSubContratacion Deserialize(string input) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(input); return((NominaReceptorSubContratacion)(Serializer.Deserialize(XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } }
public new static PredicateCompareType Deserialize(string input) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(input); return((PredicateCompareType)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } }
/// <summary> /// Must override this, this is the bit that matches up the designer properties to the dictionary values /// </summary> /// <param name="context"></param> /// <param name="collection"></param> /// <returns></returns> public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection) { //load the file if (!_loaded) { _loaded = true; LoadValuesFromFile(); } //collection that will be returned. SettingsPropertyValueCollection values = new SettingsPropertyValueCollection(); //itterate thought the properties we get from the designer, checking to see if the setting is in the dictionary foreach (SettingsProperty setting in collection) { SettingsPropertyValue value = new SettingsPropertyValue(setting); value.IsDirty = false; //need the type of the value for the strong typing var t = Type.GetType(setting.PropertyType.FullName); if (setting.PropertyType == typeof(System.Collections.Specialized.StringCollection)) { var xml = SettingsDictionary[setting.Name].value; var stringReader = new System.IO.StringReader(xml); var xmlreader = System.Xml.XmlReader.Create(stringReader); var ser = new System.Xml.Serialization.XmlSerializer(typeof(System.Collections.Specialized.StringCollection)); var obj = ser.Deserialize(xmlreader); var col = (System.Collections.Specialized.StringCollection)obj; value.PropertyValue = col; } else if (SettingsDictionary.ContainsKey(setting.Name)) { value.SerializedValue = SettingsDictionary[setting.Name].value; value.PropertyValue = Convert.ChangeType(SettingsDictionary[setting.Name].value, t); } else //use defaults in the case where there are no settings yet { value.SerializedValue = setting.DefaultValue; value.PropertyValue = Convert.ChangeType(setting.DefaultValue, t); } values.Add(value); } return(values); }
private void GetPictures(CT_GraphicalObjectData god, List <NPOI.OpenXmlFormats.Dml.Picture.CT_Picture> pictures) { XmlSerializer xmlse = new XmlSerializer(typeof(NPOI.OpenXmlFormats.Dml.Picture.CT_Picture)); foreach (string el in god.Any) { if (el.IndexOf("pic:pic") < 0) { continue; } System.IO.StringReader stringReader = new System.IO.StringReader(el); NPOI.OpenXmlFormats.Dml.Picture.CT_Picture pict = xmlse.Deserialize(System.Xml.XmlReader.Create(stringReader)) as NPOI.OpenXmlFormats.Dml.Picture.CT_Picture; pictures.Add(pict); } }
/// <summary> /// Attempts to create an SVG document from the specified string data. /// </summary> /// <param name="svg">The SVG data.</param> public static T FromSvg <T>(string svg) where T : SvgDocument, new() { if (string.IsNullOrEmpty(svg)) { throw new ArgumentNullException("svg"); } using (var strReader = new System.IO.StringReader(svg)) { var reader = new SvgTextReader(strReader, null) { XmlResolver = new SvgDtdResolver(), WhitespaceHandling = WhitespaceHandling.Significant }; return(Open <T>(reader)); } }
// Populates the CSV reader dictionary. /// <param name="fileName">Gets the path name.</param> public Dictionary <string, string> ReadFile(string fileName) { Dictionary <string, string> output = new Dictionary <string, string>(); string csvText = System.IO.File.ReadAllText(fileName); using (System.IO.StringReader reader = new System.IO.StringReader(csvText)) { string line; while ((line = reader.ReadLine()) != null) { string[] vals = line.Split(','); output.Add(vals[0], line.Substring(vals[0].Length + 1)); } } return(output); }
public string TransformXML(string xml, string xsl) { System.IO.StringReader stringReader = null; System.Xml.Xsl.XslCompiledTransform xslTransform = null; System.Xml.XmlTextReader xmlTextReader = null; System.IO.MemoryStream xmlTextWriterStream = null; System.Xml.XmlTextWriter xmlTextWriter = null; System.Xml.XmlDocument xmlDocument = null; System.IO.StreamReader streamReader = null; //System.Security.Policy.Evidence evidence = null; try { stringReader = new System.IO.StringReader(xsl); xslTransform = new System.Xml.Xsl.XslCompiledTransform(); xmlTextReader = new System.Xml.XmlTextReader(stringReader); xmlTextWriterStream = new System.IO.MemoryStream(); xmlTextWriter = new System.Xml.XmlTextWriter(xmlTextWriterStream, System.Text.Encoding.Default); xmlDocument = new System.Xml.XmlDocument(); //evidence = new System.Security.Policy.Evidence(); //evidence.AddAssembly(this); xmlDocument.LoadXml(xml); xslTransform.Load(xmlTextReader); xslTransform.Transform(xmlDocument, null, xmlTextWriter, null); xmlTextWriter.Flush(); xmlTextWriterStream.Position = 0; streamReader = new System.IO.StreamReader(xmlTextWriterStream); return(streamReader.ReadToEnd()); } catch (Exception exc) { LogEvent(exc.Source, "TransformXML()", exc.ToString(), 4); return(""); } finally { streamReader.Close(); xmlTextWriter.Close(); xmlTextWriterStream.Close(); xmlTextReader.Close(); stringReader.Close(); GC.Collect(); } }
// Display any warnings or errors. public static bool CanDeserialize(string xml) { System.IO.StringReader stringReader = null; try { var settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; stringReader = new System.IO.StringReader(xml); return(Serializer.CanDeserialize(System.Xml.XmlReader.Create(stringReader, settings))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } }
public void SetupBuilderLoadConfigurationFromXmlPatchTest() { // Arrange var xmlFile = new System.IO.StringReader("<nlog autoshutdown='true'></nlog>"); var appEnv = new Mocks.AppEnvironmentMock(f => true, f => System.Xml.XmlReader.Create(xmlFile)); var configLoader = new LoggingConfigurationFileLoader(appEnv); var logFactory = new LogFactory(configLoader); // Act logFactory.Setup(). LoadConfigurationFromXml("<nlog autoshutdown='false'></nlog>"). LoadConfigurationFromFile(). // No effect, since config already loaded LoadConfiguration(b => { b.Configuration.Variables["Hello"] = "World"; }); // Assert Assert.False(logFactory.AutoShutdown); Assert.Single(logFactory.Configuration.Variables); }
/// <summary> /// Deserializes workflow markup into an Root object /// </summary> // <param name="xml">string workflow markup to deserialize</param> // <param name="obj">Output Root object</param> // <param name="exception">output Exception value if deserialize failed</param> // <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out Root obj, out System.Exception exception) { exception = null; obj = null; try { System.IO.StringReader stringReader = new System.IO.StringReader(xml); System.Xml.XmlTextReader xmlTextReader = new System.Xml.XmlTextReader(stringReader); System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(Root)); obj = ((Root)(xmlSerializer.Deserialize(xmlTextReader))); return(true); } catch (System.Exception e) { exception = e; return(false); } }
internal ExpressionElement Parse(string expression, IServiceProvider services) { lock (_mySyncRoot) { System.IO.StringReader sr = new System.IO.StringReader(expression); ExpressionParser parser = this.Parser; parser.Reset(sr); parser.Tokenizer.Reset(sr); FleeExpressionAnalyzer analyzer = (FleeExpressionAnalyzer)parser.Analyzer; analyzer.SetServices(services); Node rootNode = DoParse(); analyzer.Reset(); ExpressionElement topElement = (ExpressionElement)rootNode.Values[0]; return(topElement); } }
private static NoteDataXML_Table LoadStringAsTable(string data) { // Loading existing table System.IO.StringReader LinkTableReader = new System.IO.StringReader(data); System.Xml.Serialization.XmlSerializer LinkTableXML = new System.Xml.Serialization.XmlSerializer(typeof(NoteDataXML_Table)); NoteDataXML_Table table = new NoteDataXML_Table(); table = (NoteDataXML_Table)LinkTableXML.Deserialize(LinkTableReader); // if (table != null) // { // MyLinkTable.SetTable (table.dataSource); // } //NewMessage.Show("Loading a link table with GUID = " + table.GuidForNote); LinkTableXML = null; LinkTableReader.Close(); LinkTableReader.Dispose(); return(table); }
public void FinallyLoad(List <GameEditorData> Risto, int i) { // porigon.blocks = Risto[i].blocks; ManagerEditor.GameName = Risto[i].Name; porigon.EditorUpdateMesh(); gameObject.SetActive(false); GEDContainer ola = new GEDContainer(); var configFile = Resources.Load("savedPatterns") as TextAsset; var serializer = new XmlSerializer(typeof(GEDContainer)); using (var reader = new System.IO.StringReader(configFile.text)) { ola = serializer.Deserialize(reader) as GEDContainer; } print("Oi, eu sou o " + ola.savedPatterns[i].Name); porigon.blocks = ConvertToMulti(ola.savedPatterns[i].blocks); porigon.EditorUpdateMesh(); }
public void LoadVals(string strXml) { XmlSerializer s; StringReader sr; CODocumentReleaseType o; s = new XmlSerializer(typeof(CODocumentReleaseType)); sr = new System.IO.StringReader(strXml); o = new CODocumentReleaseType(); o = (CODocumentReleaseType)s.Deserialize(sr); base.LoadFromObj(o); o = null; sr.Close(); sr = null; s = null; }