/// <summary> /// Parse a query string /// </summary> /// <param name="reader">string to parse</param> /// <param name="parameters">Parameter collection to fill</param> /// <returns>A collection</returns> /// <exception cref="ArgumentNullException"><c>reader</c> is <c>null</c>.</exception> public void Parse(TextReader reader, IParameterCollection parameters) { if (reader == null) throw new ArgumentNullException("reader"); var canRun = true; while (canRun) { var result = reader.ReadToEnd("&="); var name = Uri.UnescapeDataString(result.Value); switch (result.Delimiter) { case '&': parameters.Add(name, string.Empty); break; case '=': result = reader.ReadToEnd("&"); parameters.Add(name, Uri.UnescapeDataString(result.Value)); break; case char.MinValue: // EOF = no delimiter && no value if (!string.IsNullOrEmpty(name)) parameters.Add(name, string.Empty); break; } canRun = result.Delimiter != char.MinValue; } }
public static int Exec(string filename, string args, TextReader stdIn = null, TextWriter stdOut = null, TextWriter stdErr = null, Encoding encoding = null, string workingDirectory = null) { using (Process process = new Process()) { ProcessStartInfo psi = process.StartInfo; psi.RedirectStandardError = psi.RedirectStandardInput = psi.RedirectStandardOutput = true; psi.UseShellExecute = false; psi.CreateNoWindow = true; psi.FileName = filename; psi.Arguments = args; if (workingDirectory != null) psi.WorkingDirectory = workingDirectory; if (encoding != null) { psi.StandardOutputEncoding = encoding; psi.StandardErrorEncoding = encoding; } if (stdOut != null) { process.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) { stdOut.WriteLine(e.Data); }; } if (stdErr != null) { process.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) { stdErr.WriteLine(e.Data); }; } process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (stdIn != null) { if (encoding != null) { // There's no Process.Standard*Input*Encoding, so write specified encoding's raw bytes to base input stream using (var encodedStdIn = new StreamWriter(process.StandardInput.BaseStream, encoding)) encodedStdIn.Write(stdIn.ReadToEnd()); } else { using (process.StandardInput) process.StandardInput.Write(stdIn.ReadToEnd()); } } process.WaitForExit(); return process.ExitCode; } }
public override void Parse(TextReader reader, IProcessorContext context) { if (AssetPipeline.MinifyJs) { var compressor = new JavaScriptCompressor(reader.ReadToEnd()); context.Output.Write(compressor.Compress()); } else { context.Output.Write(reader.ReadToEnd()); } }
public override void Initialize(object state, TextReader textreader, SourceUnit sourceUnit, SS.SourceLocation initialLocation) { tokenizer = new Tokenizer (textreader.ReadToEnd ().ToCharArray (), new IdentifierTable ()); tokenizer.Position = ConvertToMJCSrcLocation(initialLocation); this.sourceUnit = sourceUnit; this.state = state; }
public object Deserialize (TextReader input) { if (input == null) throw new ArgumentNullException ("input"); return Deserialize (input.ReadToEnd ()); }
public override object Deserialize(TextReader tr) { string value = tr.ReadToEnd(); IStatusCode sc = CreateAndAssociate() as IStatusCode; if (sc != null) { // Decode the value as needed value = Decode(sc, value); Match match = Regex.Match(value, @"\d(\.\d+)*"); if (match.Success) { int[] iparts; string[] parts = match.Value.Split('.'); iparts = new int[parts.Length]; for (int i = 0; i < parts.Length; i++) { int num; if (!Int32.TryParse(parts[i], out num)) return false; iparts[i] = num; } sc.Parts = iparts; return sc; } } return null; }
/// <summary> /// Initializes a new instance of the <see cref="ObjectMapTable"/> class. /// </summary> /// <param name="bufferedReader">The buffered reader.</param> public ObjectMapTable(TextReader bufferedReader) : this() { try { XmlDocument XmlData = new XmlDocument(); XmlData.LoadXml(bufferedReader.ReadToEnd()); //add projects to treeview XmlNodeList Classes = XmlData.SelectNodes("ObjectMap/Class"); if (Classes != null && Classes.Count > 0) { foreach (XmlElement nodeClass in Classes) { // Add path and class to the object mapping ObjectMapping theMapping = new ObjectMapping(nodeClass); _objectMapList.Add(theMapping); } } } catch (Exception ex) { throw new Exception("error reading map file", ex); } finally { bufferedReader.Close(); } }
/// <summary> /// Searches for regex patterns in the textual input and returns them as a list of tokens. /// </summary> /// <remarks>This tokenizer does not return line number and column information.</remarks> /// <param name="inputStream">Input stream containing textual data, which should be searched for regex patterns.</param> /// <returns>Enumeration of tokens, matching the specified regex patterns.</returns> public IEnumerable <IToken> EnumerateTokens(System.IO.TextReader inputReader) { if (inputReader == null) { yield break; } string inputText = inputReader.ReadToEnd(); var matches = mPatternRegEx.Matches(inputText); // Perform regex matching foreach (System.Text.RegularExpressions.Match match in matches) { // Find first group, containing a match for (int i = 1; i < match.Groups.Count; ++i) { var currentGroup = match.Groups[i]; if (currentGroup.Success) { string token = currentGroup.Value; string tokenType = mPatternRegEx.GroupNameFromNumber(i); yield return(new Token(token, tokenType, currentGroup.Index)); } } } }
public Modification[] Parse(TextReader history, DateTime from, DateTime to) { string historyLog = history.ReadToEnd(); Regex regex = new Regex(Alienbrain.NO_CHANGE); if (regex.Match(historyLog).Success == true) { return new Modification[0]; } regex = new Regex(FILE_REGEX); var result = new List<Modification>(); string oldfile = ","; for (Match match = regex.Match(historyLog); match.Success; match = match.NextMatch()) { string[] modificationParams = AllModificationParams(match.Value); if (modificationParams.Length > 1) { string file = modificationParams[1]; if (file != oldfile) { result.Add(ParseModification(modificationParams)); oldfile = file; } } } return result.ToArray(); }
public override TokenStream TokenStream(string fieldName, TextReader reader) { // Split the title based on IdSeparators, then run it through the innerAnalyzer string title = reader.ReadToEnd(); string partiallyTokenized = String.Join(" ", title.Split(LuceneIndexingService.IdSeparators, StringSplitOptions.RemoveEmptyEntries)); return innerAnalyzer.TokenStream(fieldName, new StringReader(partiallyTokenized)); }
public StringTokenizer(TextReader reader) { if (reader == null) throw new ArgumentNullException("reader"); data = reader.ReadToEnd(); Reset(); }
public Feature Parse(TextReader featureFileReader) { var fileContent = featureFileReader.ReadToEnd() + Environment.NewLine; CultureInfo language = GetLanguage(fileContent); var inputStream = new ANTLRReaderStream(new StringReader(fileContent)); var lexer = GetLexter(language, inputStream); var tokenStream = new CommonTokenStream(lexer); var parser = new Grammar.SpecFlowLangParser(tokenStream); var featureTree = parser.feature().Tree as CommonTree; if (featureTree == null || parser.ParserErrors.Count > 0 || lexer.LexerErrors.Count > 0) { throw new SpecFlowParserException("Invalid Gherkin file!", lexer.LexerErrors.Concat(parser.ParserErrors).ToArray()); } var walker = new SpecFlowLangWalker(new CommonTreeNodeStream(featureTree)); Feature feature = walker.feature(); if (feature == null) throw new SpecFlowParserException("Invalid Gherkin file!"); feature.Language = language.Name; return feature; }
/// <summary> /// Assembles a document from the given template, answers and settings. /// </summary> /// <param name="template">The template to assemble.</param> /// <param name="answers">The answers to use during the assembly.</param> /// <param name="settings">The settings for the assembly.</param> /// <include file="../../Shared/Help.xml" path="Help/string/param[@name='logRef']"/> /// <returns>An <c>AssembleDocumentResult</c> that contains the results of the assembly.</returns> public AssembleDocumentResult AssembleDocument(Template template, System.IO.TextReader answers, AssembleDocumentSettings settings, string logRef) { // Validate input parameters, creating defaults as appropriate. string logStr = logRef == null ? string.Empty : logRef; if (template == null) { throw new ArgumentNullException("template", string.Format(@"Cloud.Services.AssembleDocument: the ""template"" parameter passed in was null, logRef: {0}", logStr)); } if (settings == null) { settings = new AssembleDocumentSettings(); } AssembleDocumentResult result = null; AssemblyResult asmResult = null; using (var client = new SoapClient(_subscriberID, _signingKey, HostAddress, ProxyAddress)) { asmResult = client.AssembleDocument( template, answers == null ? "" : answers.ReadToEnd(), settings, logRef ); } if (asmResult != null) { result = Util.ConvertAssemblyResult(template, asmResult, settings.Format); } return(result); }
/// <inheritdoc /> public IParseForest Parse(TextReader reader) { // CONTRACT: Inherited from IParser // Unger requires the whole input to be known beforehand. return Parse(reader.ReadToEnd()); }
/// <summary> /// Parses the specified pattern returned by the reader and localizes error messages with the text manager specified /// </summary> /// <param name="reader">The reader.</param> /// <param name="textManager">The text manager.</param> /// <returns></returns> public override Expression Parse(TextReader reader, TextManager textManager) { try { _reader = reader.ReadToEnd(); _pos = -1; MoveNext(); var expr = ParseExpression(); if (_current != Eof) { UnexpectedToken("Expression", "" + _current); } expr.Accept(_trimmer); return expr; } catch (InnerParserException template) { throw new SyntaxErrorException(template.Message, template.Construct, template.Pos); } }
public override ParsedDocument Parse (bool storeAst, string fileName, TextReader reader, Project project = null) { var doc = new DefaultParsedDocument (fileName); doc.Flags |= ParsedDocumentFlags.NonSerializable; ProjectInformation pi = ProjectInformationManager.Instance.Get (project); string content = reader.ReadToEnd (); string[] contentLines = content.Split (new string[]{Environment.NewLine}, StringSplitOptions.None); var globals = new DefaultUnresolvedTypeDefinition ("", GettextCatalog.GetString ("(Global Scope)")); lock (pi) { // Add containers to type list foreach (LanguageItem li in pi.Containers ()) { if (null == li.Parent && FilePath.Equals (li.File, fileName)) { var tmp = AddLanguageItem (pi, globals, li, contentLines) as IUnresolvedTypeDefinition; if (null != tmp){ doc.TopLevelTypeDefinitions.Add (tmp); } } } // Add global category for unscoped symbols foreach (LanguageItem li in pi.InstanceMembers ()) { if (null == li.Parent && FilePath.Equals (li.File, fileName)) { AddLanguageItem (pi, globals, li, contentLines); } } } doc.TopLevelTypeDefinitions.Add (globals); return doc; }
/// <summary> /// Enumerates all tags contained in the input text. /// </summary> /// <param name="inputReader">Input reader containing textual data, which should be scanned for tags.</param> /// <returns>Enumeration of tag tokens. The data field of the token contains an array of TagInfo objects.</returns> public IEnumerable <IToken> EnumerateTokens(System.IO.TextReader inputReader) { if (inputReader == null) { yield break; } string inputText = inputReader.ReadToEnd(); var matches = mTagPatternRegex.Matches(inputText); // Perform regex matching foreach (Match match in matches) { var tagGroup = match.Groups["TAG"]; if (tagGroup.Success) { var tagToken = new Token(tagGroup.Value, TOKEN_TYPE_TAG, GetTagData(match).ToArray(), tagGroup.Index); if (OnTag != null) { OnTag(tagToken); } yield return(tagToken); } } }
public object Parse(TextReader sourceReader) { if (sourceReader == null) throw new ArgumentNullException("sourceReader"); return Parse(new TextParser(sourceReader.ReadToEnd())); }
public override TokenStream TokenStream(string fieldName, TextReader reader) { string str = reader.ReadToEnd(); StringBuilder builder = new StringBuilder(str); builder.Replace('.', ' '); builder.Replace('<', ' '); builder.Replace('>', ' '); builder.Replace('[', ' '); builder.Replace(']', ' '); builder.Replace('(', ' '); builder.Replace(')', ' '); builder.Replace(',', ' '); builder.Replace(" ", " "); str = builder.ToString(); for (int i = builder.Length - 1; i > 0; i--) { if (char.IsUpper(builder[i])) builder.Insert(i, ' '); } builder.Append(' ').Append(str); return new LowerCaseFilter(new WhitespaceTokenizer(new StringReader(builder.ToString()))); }
public override object Deserialize(TextReader tr) { if (tr != null) { string value = tr.ReadToEnd(); ICalendarObject co = SerializationContext.Peek() as ICalendarObject; if (co != null) { EncodableDataType dt = new EncodableDataType(); dt.AssociatedObject = co; value = Decode(dt, value); } value = TextUtil.Normalize(value, SerializationContext).ReadToEnd(); try { Uri uri = new Uri(value); return uri; } catch { } } return null; }
public CaseCollection Read(TextReader textReader) { // Clean up any invalid XML string originalXml = textReader.ReadToEnd(); string validXml = ReEncodeAttributeValues(originalXml); var stringReader = new StringReader(validXml); var testCollection = new CaseCollection(); XDocument doc = XDocument.Load(stringReader); // Check for <testcases> XElement rootElement = doc.Elements().FirstOrDefault(i => i.Name.LocalName == "testcases"); if (rootElement == null) throw new TestCaseException("<testcases> node is missing from the config file."); // Repeats int repeatValue = 0; string repeatAttribute = XmlHelper.GetOptionalAttribute(rootElement, "repeat"); int.TryParse(repeatAttribute, out repeatValue); testCollection.Repeat = repeatValue; // <testvar> testCollection.Variables = GetTestVars(rootElement); // <case> - add each one and re-order them by their id="" attribute. var testCases = new List<Case>(); foreach (XElement element in rootElement.Elements().Where(x => x.Name.LocalName == "case")) { Case testCase = GetTestCase(element); testCases.Add(testCase); } testCollection.TestCases = testCases.OrderBy(x => x.Id); return testCollection; }
public static IEnumerable<HandlebarsToken> Tokenize(TextReader templateReader) { var template = templateReader.ReadToEnd(); var matches = handlebars.Matches(template); var index = 0; foreach (Match match in matches) { if (index < match.Index) { yield return new HandlebarsToken(false, template.Substring(index, match.Index - index), false, false, false, index, match.Index - index); } var token = match.Value.Trim(); var isHtmlEscape = token.Count(c => c == '{') == 2; token = token.Trim('{', '}'); var trimLastLiteral = token.StartsWith("~"); var trimNextLiteral = token.EndsWith("~"); token = token.Trim('~').Trim(); yield return new HandlebarsToken(true, token, isHtmlEscape, trimLastLiteral, trimNextLiteral, match.Index + match.Value.IndexOf(token, StringComparison.Ordinal), token.Length); index = match.Index + match.Length; } if (index < template.Length) { yield return new HandlebarsToken(false, template.Substring(index), false, false, false, index, template.Length - index); } }
public ReaderPackageJsonSource(TextReader reader) { try { var text = reader.ReadToEnd(); try { // JsonConvert and JObject.Parse exhibit slightly different behavior, // so fall back to JObject.Parse if JsonConvert does not properly deserialize // the object. Package = JsonConvert.DeserializeObject(text); } catch (ArgumentException) { Package = JObject.Parse(text); } } catch (JsonReaderException jre) { WrapExceptionAndRethrow(jre); } catch (JsonSerializationException jse) { WrapExceptionAndRethrow(jse); } catch (FormatException fe) { WrapExceptionAndRethrow(fe); } catch (ArgumentException ae) { throw new PackageJsonException( string.Format(CultureInfo.CurrentCulture, @"Error reading package.json. The file may be parseable JSON but may contain objects with duplicate properties. The following error occurred: {0}", ae.Message), ae); } }
public override object Deserialize(TextReader tr) { string value = tr.ReadToEnd(); // Create the day specifier and associate it with a calendar object IWeekDay ds = CreateAndAssociate() as IWeekDay; // Decode the value, if necessary value = Decode(ds, value); Match match = Regex.Match(value, @"(\+|-)?(\d{1,2})?(\w{2})"); if (match.Success) { if (match.Groups[2].Success) { ds.Offset = Convert.ToInt32(match.Groups[2].Value); if (match.Groups[1].Success && match.Groups[1].Value.Contains("-")) ds.Offset *= -1; } ds.DayOfWeek = RecurrencePatternSerializer.GetDayOfWeek(match.Groups[3].Value); return ds; } return null; }
/// <summary> /// Parse and filter the supplied modifications. The position of each modification in the list is used as the ChangeNumber. /// </summary> /// <param name="history"></param> /// <param name="from"></param> /// <param name="to"></param> /// <returns></returns> public Modification[] Parse(TextReader history, DateTime from, DateTime to) { StringReader sr = new StringReader(string.Format(@"<ArrayOfModification xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">{0}</ArrayOfModification>" , history.ReadToEnd())); XmlSerializer serializer = new XmlSerializer(typeof(Modification[])); Modification[] mods; try { mods = (Modification[])serializer.Deserialize(sr); } catch (Exception ex) { throw new CruiseControlException("History Parsing Failed", ex); } ArrayList results = new ArrayList(); int change = 0; foreach (Modification mod in mods) { change++; mod.ChangeNumber = change; if ((mod.ModifiedTime >= from) & (mod.ModifiedTime <= to)) { results.Add(mod); } } return (Modification[])results.ToArray(typeof(Modification)); }
/// <summary> /// Execute script from stream. /// </summary> public void Execute(TextReader reader) { // Read script string script = reader.ReadToEnd(); // Execute ExecuteScriptText(script); }
/// <summary> /// Read CSV-formatted data from a TextReader /// </summary> /// <param name="reader">TextReader that's reading CSV-formatted data</param> public CSVReader(TextReader reader) { if (reader == null) throw new ArgumentNullException("Null TextReader passed to CSVReader"); this.reader = new BinaryReader(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(reader.ReadToEnd()))); }
public static void LoadHtmlFile( System.IO.TextReader reader, DomDocument document, string baseUrl) { if (reader == null) { throw new ArgumentNullException("reader"); } if (document == null) { throw new ArgumentNullException("document"); } HTMLDocument htmlDoc = new HTMLDocument(); string html = reader.ReadToEnd(); htmlDoc.LoadHTML(html); if (string.IsNullOrEmpty(baseUrl) == false) { htmlDoc.BaseURL = baseUrl; } HtmlLoader loader = new HtmlLoader(); loader.Load(htmlDoc, document); document.AfterLoad(FileFormat.Html); }
public Solution Parse(TextReader sr) { var sln = new Solution(); string content = sr.ReadToEnd(); const string pattern = @"\nProject\(""\{[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-Z0-9]{12}\}""\)\s*=\s*""(?<projName>[^""]+)"", ""(?<projPath>[^""]+)"",\s*""\{(?<projGuid>[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-Z0-9]{12})\}"""; var regexObj = new Regex(pattern, RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.ExplicitCapture); Match match = regexObj.Match(content); while (match.Success) { string projName = match.Groups["projName"].Value; string projPath = match.Groups["projPath"].Value; string projGuid = match.Groups["projGuid"].Value.ToUpperInvariant(); if (String.Compare(Path.GetExtension(projPath), ".csproj", true, CultureInfo.InvariantCulture) == 0) { sln.Projects.Add(new SolutionProject { Name = projName, Path = projPath, Guid = projGuid }); } match = match.NextMatch(); } return sln; }
public TemplateParser (string filename, TextReader input) { this.filename = filename; fileText = input.ReadToEnd (); StringReader reader = new StringReader (fileText); tokenizer = new TemplateTokenizer (reader); }
public override object Deserialize(TextReader tr) { string value = tr.ReadToEnd(); IPeriod p = CreateAndAssociate() as IPeriod; ISerializerFactory factory = GetService<ISerializerFactory>(); if (p != null && factory != null) { IStringSerializer dtSerializer = factory.Build(typeof(IDateTime), SerializationContext) as IStringSerializer; IStringSerializer durationSerializer = factory.Build(typeof(TimeSpan), SerializationContext) as IStringSerializer; if (dtSerializer != null && durationSerializer != null) { // Decode the value as necessary value = Decode(p, value); string[] values = value.Split('/'); if (values.Length != 2) return false; p.StartTime = dtSerializer.Deserialize(new StringReader(values[0])) as IDateTime; p.EndTime = dtSerializer.Deserialize(new StringReader(values[1])) as IDateTime; if (p.EndTime == null) p.Duration = (TimeSpan)durationSerializer.Deserialize(new StringReader(values[1])); // Only return an object if it has been deserialized correctly. if (p.StartTime != null && p.Duration != null) return p; } } return null; }
public override object Deserialize(TextReader tr) { string value = tr.ReadToEnd(); IUTCOffset offset = CreateAndAssociate() as IUTCOffset; if (offset != null) { // Decode the value as necessary value = Decode(offset, value); Match match = Regex.Match(value, @"(\+|-)(\d{2})(\d{2})(\d{2})?"); if (match.Success) { try { // NOTE: Fixes bug #1874174 - TimeZone positive UTCOffsets don't parse correctly if (match.Groups[1].Value == "+") offset.Positive = true; offset.Hours = Int32.Parse(match.Groups[2].Value); offset.Minutes = Int32.Parse(match.Groups[3].Value); if (match.Groups[4].Success) offset.Seconds = Int32.Parse(match.Groups[4].Value); } catch { return null; } return offset; } return false; } return null; }
public override object Deserialize(TextReader tr) { string value = tr.ReadToEnd(); IGeographicLocation g = CreateAndAssociate() as IGeographicLocation; if (g != null) { // Decode the value, if necessary! value = Decode(g, value); string[] values = value.Split(';'); if (values.Length != 2) return false; double lat; double lon; double.TryParse(values[0], out lat); double.TryParse(values[1], out lon); g.Latitude = lat; g.Longitude = lon; return g; } return null; }
public override TokenStream TokenStream(string fieldName, TextReader reader) { string str = reader.ReadToEnd(); string[] parts = str.Split('.'); StringBuilder tokenString = new StringBuilder(); for (int i = 0; i < parts.Length; i++) { if (parts[i].IndexOf('(') > 0) parts[i] = parts[i].Substring(0, parts[i].IndexOf('(')); if (parts[i].IndexOf('<') > 0) parts[i] = parts[i].Substring(0, parts[i].IndexOf('<')); parts[i] = new string(parts[i].Where(c => char.IsUpper(c) || char.IsNumber(c)).ToArray()); } tokenString.AppendLine(parts[parts.Length - 1]); for (int i = parts.Length - 2; i >= 0; i--) { tokenString.AppendLine(string.Join(".", parts, i, parts.Length - i)); } return new WhitespaceTokenizer(new StringReader(tokenString.ToString().ToLowerInvariant())); }
public TestTokenizer(System.IO.TextReader reader) : base(reader) { //Caution: "Reader" is actually of type "ReusableStringReader" and some //methods (for ex. "ReadToEnd", "Peek", "ReadLine") is not implemented. Assert.AreEqual("ReusableStringReader", reader.GetType().Name); Assert.AreEqual("First Line", reader.ReadLine(), "\"ReadLine\" method is not implemented"); Assert.AreEqual("Second Line", reader.ReadToEnd(), "\"ReadToEnd\" method is not implemented"); }
public void DeSerializeState(System.IO.TextReader reader) { if (_listControl.Columns.Count == 0) { _deferredSerializationState = reader.ReadToEnd(); } else { _listControl.DeSerializeState(reader); _deferredSerializationState = null; } }
private void butOpenFile_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) { if (cdbOpen.ShowDialog() == DialogResult.OK) { this.txtFile.Clear(); System.IO.TextReader tr = File.OpenText(cdbOpen.FileName); this.txtFile.Text = tr.ReadToEnd(); tr.Close(); tr = null; } }
public static void SetLicense() { string p_Lic, p_Key; //1、读取License文件 //License文件夹被我放到Debug文件夹和Release文件夹里,可以根据需要变更文件路径 System.IO.TextReader reader = System.IO.File.OpenText(@"License\full_license.key"); p_Key = reader.ReadLine(); reader = System.IO.File.OpenText(@"License\full_license.lic"); p_Lic = reader.ReadToEnd(); //下面只是注册License的其中一中方式 byte[] licenseBuffer = ASCIIEncoding.ASCII.GetBytes(p_Lic.ToCharArray()); RasterSupport.ResetLicense(); RasterSupport.SetLicense(licenseBuffer, p_Key); }
/// <summary> /// Parse an arbitrary stream /// </summary> public override CodeCompileUnit Parse(System.IO.TextReader codeStream) { // get a better filename if we can string name = "<unknown>"; StreamReader sw = codeStream as StreamReader; if (sw != null) { FileStream fs = sw.BaseStream as FileStream; if (fs != null) { name = fs.Name; } } //!!! it'd be nice to have Parser.FromStream to get proper decodings here string codeText = codeStream.ReadToEnd(); CodeCompileUnit tree = Parse(Parser.FromString(state, new CompilerContext(), codeText), name); CodeMerger.CacheCode(tree, codeText); return(tree); }
public override string ReadToEnd() => _in.ReadToEnd();
public override string ReadToEnd() { lock (this){ return(reader.ReadToEnd()); } }
public override String ReadToEnd() { return(_in.ReadToEnd()); }
// research: https://www.youtube.com/watch?v=6Yf-eDsRrnM public static void Main(string[] args) { // pre UI //"C:\Program Files (x86)\WiX Toolset v3.11\bin\candle" -ext "C:\Program Files (x86)\WiX Toolset v3.11\bin\WixNetFxExtension.dll" .\output\output.xml //"C:\Program Files (x86)\WiX Toolset v3.11\bin\light" -ext "C:\Program Files (x86)\WiX Toolset v3.11\bin\WixNetFxExtension.dll" output.wixobj // Post UI //"C:\Program Files (x86)\WiX Toolset v3.11\bin\candle" -ext "C:\Program Files (x86)\WiX Toolset v3.11\bin\WixNetFxExtension.dll" -ext "C:\Program Files (x86)\WiX Toolset v3.11\bin\WixUIExtension.dll" .\output\output.xml //"C:\Program Files (x86)\WiX Toolset v3.11\bin\light" -ext "C:\Program Files (x86)\WiX Toolset v3.11\bin\WixNetFxExtension.dll" -ext "C:\Program Files (x86)\WiX Toolset v3.11\bin\WixUIExtension.dll" -cultures:en-us output.wixobj string major_version = "18.02.22"; string minor_version = "3db277d"; string current_version = $"{major_version} v({minor_version})"; if (args.Length > 0) { for (var i = 1; i < args.Length; i++) { string arg = args [i]; int index = arg.IndexOf(':'); string val = arg.Substring(index + 1, arg.Length - (index + 1)).Trim(new char [] { '\"' }); if (arg.ToLower().StartsWith("wix_directory_path")) { wix_directory_path = val; } else if (arg.ToLower().StartsWith("build_directory_path")) { build_directory_path = val; } else if (arg.ToLower().StartsWith("input_directory_path")) { input_directory_path = val; } else if (arg.ToLower().StartsWith("output_directory_path")) { output_directory_path = val; } else if (arg.ToLower().StartsWith("mmria_server_binary_directory_path")) { mmria_server_binary_directory_path = val; } else if (arg.ToLower().StartsWith("mmria_console_binary_directory_path")) { mmria_console_binary_directory_path = val; } else if (arg.ToLower().StartsWith("mmria_server_html_directory_path")) { mmria_server_html_directory_path = val; } } } if (string.IsNullOrWhiteSpace(wix_directory_path)) { wix_directory_path = System.Configuration.ConfigurationManager.AppSettings["wix_directory_path"]; } if (string.IsNullOrWhiteSpace(build_directory_path)) { build_directory_path = System.Configuration.ConfigurationManager.AppSettings ["build_directory_path"]; } if (string.IsNullOrWhiteSpace(input_directory_path)) { input_directory_path = System.Configuration.ConfigurationManager.AppSettings["input_directory_path"]; } if (string.IsNullOrWhiteSpace(output_directory_path)) { output_directory_path = System.Configuration.ConfigurationManager.AppSettings["output_directory_path"]; } if (string.IsNullOrWhiteSpace(mmria_server_binary_directory_path)) { mmria_server_binary_directory_path = System.Configuration.ConfigurationManager.AppSettings ["mmria_server_binary_directory_path"]; } if (string.IsNullOrWhiteSpace(mmria_console_binary_directory_path)) { mmria_console_binary_directory_path = System.Configuration.ConfigurationManager.AppSettings ["mmria_console_binary_directory_path"]; } if (string.IsNullOrWhiteSpace(mmria_server_html_directory_path)) { mmria_server_html_directory_path = System.Configuration.ConfigurationManager.AppSettings ["mmria_server_html_directory_path"]; } if (System.IO.Directory.Exists(input_directory_path)) { System.IO.Directory.Delete(input_directory_path, true); } if (System.IO.Directory.Exists(output_directory_path)) { System.IO.Directory.Delete(output_directory_path, true); } if (System.IO.File.Exists(build_directory_path + @"\output.wixobj")) { System.IO.File.Delete(build_directory_path + @"\output.wixobj"); } if (System.IO.File.Exists(build_directory_path + @"\output.wixpdb")) { System.IO.File.Delete(build_directory_path + @"\output.wixpdb"); } if (System.IO.File.Exists(build_directory_path + @"\output.msi")) { System.IO.File.Delete(build_directory_path + @"\output.msi"); } CopyFolder.CopyDirectory(mmria_server_binary_directory_path, input_directory_path); CopyFolder.CopyDirectory(mmria_server_html_directory_path, input_directory_path + "/app"); CopyFolder.CopyDirectory(mmria_console_binary_directory_path + "/mapping-file-set", input_directory_path + "/mapping-file-set"); File.Copy(mmria_console_binary_directory_path + "/mmria.exe", input_directory_path + "/mmria.exe"); File.Copy(mmria_console_binary_directory_path + "/mmria.pdb", input_directory_path + "/mmria.pdb"); File.Copy(mmria_console_binary_directory_path + "/LumenWorks.Framework.IO.dll", input_directory_path + "/LumenWorks.Framework.IO.dll"); File.Copy("./mmria.exe.config", input_directory_path + "/mmria.exe.config", true); File.Copy("./mmria-server.exe.config", input_directory_path + "/mmria-server.exe.config", true); // version number -- Start System.Text.RegularExpressions.Regex version_tag = new System.Text.RegularExpressions.Regex("<\\%=version\\%>"); string profile_text = System.IO.File.ReadAllText(input_directory_path + "/app/scripts/profile.js"); System.IO.File.WriteAllText(input_directory_path + "/app/scripts/profile.js", version_tag.Replace(profile_text, current_version)); string index_text = System.IO.File.ReadAllText(input_directory_path + "/app/index.html"); System.IO.File.WriteAllText(input_directory_path + "/app/index.html", version_tag.Replace(index_text, current_version)); // version number -- End // remove unneeded files -- start if (System.IO.Directory.Exists(input_directory_path + "/app/metadata")) { System.IO.Directory.Delete(input_directory_path + "/app/metadata", true); } if (File.Exists(input_directory_path + "/app/grid-test-1.html")) { File.Delete(input_directory_path + "/app/grid-test-1.html"); } if (File.Exists(input_directory_path + "/app/grid-test-2.html")) { File.Delete(input_directory_path + "/app/grid-test-2.html"); } if (File.Exists(input_directory_path + "/app/grid-test-3.html")) { File.Delete(input_directory_path + "/app/grid-test-3.html"); } if (File.Exists(input_directory_path + "/app/socket-test.html")) { File.Delete(input_directory_path + "/app/socket-test.html"); } if (File.Exists(input_directory_path + "/app/socket-test2.html")) { File.Delete(input_directory_path + "/app/socket-test2.html"); } // remove uneeded files -- end // version number.... /* * * * * cp "${source_code_directory}/owin/psk/app/scripts/profile.js" "$wix_root_directory/profile.js.bk" && \ * cp "${source_code_directory}/owin/psk/app/index.html" "$wix_root_directory/index.html.bk" && \ * sed -e 's/<\%=version\%>/'$current_year'.'$current_month'.'$current_day' v('$current_build')/g' "${wix_root_directory}/profile.js.bk" > "${wix_root_directory}/profile.js" && \ * sed -e 's/<\%=version\%>/'$current_year'.'$current_month'.'$current_day' v('$current_build')/g' "${wix_root_directory}/index.html.bk" > "${wix_root_directory}/index.html" && \ * rm -f "$wix_input_directory/app/scripts/profile.js" && cp "$wix_root_directory/profile.js" "$wix_input_directory/app/scripts/profile.js" && \ * rm -f "$wix_input_directory/app/index.html" && cp "$wix_root_directory/index.html" "$wix_input_directory/app/index.html" * * * * * * File.Copy(mmria_console_binary_directory_path + "/", input_directory_path + "/"); * File.Copy(mmria_console_binary_directory_path + "/", input_directory_path + "/"); * File.Copy(mmria_console_binary_directory_path + "/", input_directory_path + "/"); * File.Copy(mmria_console_binary_directory_path + "/", input_directory_path + "/"); * File.Copy(mmria_console_binary_directory_path + "/", input_directory_path + "/"); * * * * * File.Copy(mmria_console_binary_directory_path + "/", input_directory_path + "/"); * File.Copy(mmria_console_binary_directory_path + "/", input_directory_path + "/"); */ CopyFolder.CopyDirectory(input_directory_path, output_directory_path); //Console.WriteLine("Hello World!"); string name_hash_file_name = "id.csv"; string wix_output_msi_file_name = $"MMRIA-Install-{current_version}.msi"; string wix_file_name = "output.xml"; name_hash_list = new System.Collections.Generic.Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); if (System.IO.File.Exists(name_hash_file_name)) { using (System.IO.TextReader reader = System.IO.File.OpenText(name_hash_file_name)) { string file = reader.ReadToEnd(); string[] line_list = file.Split('\n'); for (int i = 0; i < line_list.Length; i++) { string[] name_hash = line_list[i].Split(','); if (name_hash.Length > 1) { name_hash_list.Add(name_hash[0].Trim(), name_hash[1].Trim()); } } } } string xml = get_xml_template(); var xmlReader = XmlReader.Create(new StringReader(xml)); XDocument wix_doc = XDocument.Load(xmlReader); var namespaceManager = new XmlNamespaceManager(xmlReader.NameTable); namespaceManager.AddNamespace("prefix", "http://schemas.microsoft.com/wix/2006/wi"); XElement ProductElement = wix_doc.XPathSelectElement("prefix:Wix/prefix:Product", namespaceManager); ProductElement.Attribute("Id").SetValue(get_id("PRODUCT_ID")); ProductElement.Attribute("UpgradeCode").SetValue(get_id("PRODUCT_UPGRADECODE")); Console.WriteLine("Product"); Console.WriteLine(ProductElement.Attribute("Name")); Console.WriteLine(ProductElement.Attribute("Id")); Console.WriteLine(ProductElement.Attribute("UpgradeCode")); Console.WriteLine(ProductElement.Attribute("Manufacturer")); Console.WriteLine(ProductElement.Attribute("Version")); XElement PackageElement = ProductElement.XPathSelectElement("./prefix:Package", namespaceManager); Console.WriteLine("Package"); Console.WriteLine(PackageElement.Attribute("Description")); Console.WriteLine(PackageElement.Attribute("Comments")); Console.WriteLine(PackageElement.Attribute("Manufacturer")); //Console.WriteLine(PackageElement.Attribute("Manufacturer")); //Console.WriteLine(PackageElement.Attribute("Version")); XElement MediaElement = ProductElement.XPathSelectElement("./prefix:Media", namespaceManager); Console.WriteLine("Media"); Console.WriteLine(MediaElement.Attribute("Cabinet")); XElement PropertyElement = ProductElement.XPathSelectElement("./prefix:Property", namespaceManager); Console.WriteLine("Property"); Console.WriteLine(PropertyElement.Attribute("Id")); Console.WriteLine(PropertyElement.Attribute("Value")); XElement IconElement = ProductElement.XPathSelectElement("./prefix:Icon", namespaceManager); Console.WriteLine("Icon"); print_xattribute(IconElement.Attribute("Id"), IconElement.Attribute("SourceFile")); XElement DirectoryElement = ProductElement.XPathSelectElement(".//prefix:Directory[@Id='INSTALLDIR']", namespaceManager); Console.WriteLine("Directory"); print_xattribute(DirectoryElement.Attribute("Id"), DirectoryElement.Attribute("Name")); XElement FeatureElement = ProductElement.XPathSelectElement("./prefix:Feature", namespaceManager); Console.WriteLine("Feature"); print_xattribute(FeatureElement.Attribute("Id"), FeatureElement.Attribute("Level")); // removed components and features foreach (XElement ComponentElement in ProductElement.XPathSelectElements(".//prefix:Component", namespaceManager).ToList()) { if (ComponentElement.Attribute("Id").Value != "ProgramMenuDir") { ComponentElement.Remove(); } } foreach (XElement ComponentRefElement in FeatureElement.XPathSelectElements(".//prefix:ComponentRef", namespaceManager).ToList()) { if (ComponentRefElement.Attribute("Id").Value != "ProgramMenuDir") { ComponentRefElement.Remove(); } } AddComponents(DirectoryElement, FeatureElement, new System.IO.DirectoryInfo(output_directory_path)); Console.WriteLine("Components"); foreach (XElement ComponentElement in ProductElement.XPathSelectElements(".//prefix:Component", namespaceManager)) { ComponentElement.Attribute("Guid").SetValue(get_id(ComponentElement.Attribute("Id").Value)); print_xattribute(ComponentElement.Attribute("Id"), ComponentElement.Attribute("Guid")); XElement FileElement = ComponentElement.XPathSelectElement("./prefix:File", namespaceManager); if (FileElement != null) { print_xattribute(FileElement.Attribute("Id"), FileElement.Attribute("Name")); } /* * XElement new_node = new_file_node(); * new_node.Add(new_short_cut_node()); * ComponentElement.Add(new_node); */ } Console.WriteLine("ComponentRefs"); foreach (XElement ComponentRefElement in ProductElement.XPathSelectElements(".//prefix:ComponentRef", namespaceManager)) { print_xattribute(ComponentRefElement.Attribute("Id")); } wix_doc.Save(wix_file_name); System.Text.RegularExpressions.Regex major_version_tag = new System.Text.RegularExpressions.Regex("<\\%=major_version\\%>"); System.Text.RegularExpressions.Regex minor_version_tag = new System.Text.RegularExpressions.Regex("<\\%=minor_version\\%>"); string text = File.ReadAllText(wix_file_name); text = System.Text.RegularExpressions.Regex.Replace(text, "xmlns=\"\"", ""); text = major_version_tag.Replace(text, major_version); text = minor_version_tag.Replace(text, minor_version); File.WriteAllText(Path.Combine(output_directory_path, wix_file_name), text); System.Text.StringBuilder name_hash_file_builder = new StringBuilder(); foreach (System.Collections.Generic.KeyValuePair <string, string> kvp in name_hash_list) { name_hash_file_builder.Append(kvp.Key); name_hash_file_builder.Append(","); name_hash_file_builder.AppendLine(kvp.Value); } System.IO.File.WriteAllText(name_hash_file_name, name_hash_file_builder.ToString()); //var FieldsTypeIDs = from _FieldTypeID in wix_doc.Descendants("Field") select _FieldTypeID; //double width, height; //string checkcode = ViewElement.Attribute("CheckCode").Value.ToString(); /* * * StringBuilder JavaScript = new StringBuilder(); * StringBuilder VariableDefinitions = new StringBuilder(); * * XDocument xdocResponse = XDocument.Parse(""); * * XDocMetadata.RequiredFieldsList = xdocResponse.Root.Attribute("RequiredFieldsList").Value; * XDocMetadata.HiddenFieldsList = xdocResponse.Root.Attribute("HiddenFieldsList").Value; * XDocMetadata.HighlightedFieldsList = xdocResponse.Root.Attribute("HighlightedFieldsList").Value; * XDocMetadata.DisabledFieldsList = xdocResponse.Root.Attribute("DisabledFieldsList").Value; * */ //System.IO.File.Copy ("./mmria.exe.config", System.IO.Path.Combine (output_directory_path, "mmria.exe.config"), true); //System.IO.File.Copy ("./mmria-server.exe.config", System.IO.Path.Combine (output_directory_path, "mmria-server.exe.config"), true); //"C:\Program Files (x86)\WiX Toolset v3.11\bin\candle" -ext "C:\Program Files (x86)\WiX Toolset v3.11\bin\WixNetFxExtension.dll" .\output\output.xml //"C:\Program Files (x86)\WiX Toolset v3.11\bin\light" -ext "C:\Program Files (x86)\WiX Toolset v3.11\bin\WixNetFxExtension.dll" output.wixobj execute_shell(build_directory_path, wix_directory_path + @"\bin\candle", @" -ext ""C:\Program Files (x86)\WiX Toolset v3.11\bin\WixNetFxExtension.dll"" -ext ""C:\Program Files (x86)\WiX Toolset v3.11\bin\WixUIExtension.dll"" .\output\output.xml"); execute_shell(build_directory_path, wix_directory_path + @"\bin\light", @" -ext ""C:\Program Files (x86)\WiX Toolset v3.11\bin\WixNetFxExtension.dll"" -ext ""C:\Program Files (x86)\WiX Toolset v3.11\bin\WixUIExtension.dll"" -cultures:en-us .\output.wixobj"); System.IO.File.Copy(build_directory_path + "/output.msi", build_directory_path + "/" + wix_output_msi_file_name, true); System.IO.File.Delete(build_directory_path + "/output.msi"); install.setup.util.cFolderCompressor folder_compressor = new install.setup.util.cFolderCompressor(); folder_compressor.Compress ( System.IO.Path.Combine(System.IO.Path.Combine(build_directory_path, wix_output_msi_file_name.Replace(".msi", ".zip"))), null, // string password System.IO.Path.Combine(System.IO.Path.Combine(build_directory_path, "output")) ); }