/// <summary>DecodeRedirect</summary> /// <param name="queryString">string</param> /// <returns>デコードされたsaml</returns> public static string DecodeRedirect(string queryString) { // EcodeRedirectの逆 // -------------------------------------------------- // Saml → URLデコード → Base64デコード // → DEFLATE解凍 → XML宣言のエンコーディング → XML // -------------------------------------------------- // Samlの抽出 string saml = ""; if (queryString.IndexOf("SAMLRequest") != -1) { saml = StringExtractor.GetParameterFromQueryString("SAMLRequest", queryString); } else if (queryString.IndexOf("SAMLResponse") != -1) { saml = StringExtractor.GetParameterFromQueryString("SAMLResponse", queryString); } else { return(""); } byte[] tempByte = DeflateCompression.Decompress( CustomEncode.FromBase64String(CustomEncode.UrlDecode(saml))); //// XML宣言部分を取得するために、us_asciiでデコード //string tempString = CustomEncode.ByteToString(tempByte, CustomEncode.us_ascii); //// エンコーディング オブジェクトの取得 //Encoding enc = XmlLib.GetEncodingFromXmlDeclaration(tempString); return(CustomEncode.ByteToString(tempByte, CustomEncode.us_ascii)); // enc.CodePage); }
public void Extract_The_Correct_String_Value() { // arrange var extractor = new StringExtractor(); var builder = new ClrObjectBuilder(); builder .WithType("System.String") .WithAddress(0x1234) .WithSize(100) .WithSimpleValue("Duke the corgi"); var runtimeBuilder = new ClrRuntimeBuilder(); var heapBuilder = new ClrHeapBuilder(); heapBuilder.WithGetGeneration(2); runtimeBuilder.WithHeap(heapBuilder.Build()); var runtime = runtimeBuilder.Build(); var built = builder.Build(); // act var result = (StringDumpObject)extractor.Extract(built, runtime); // assert result.Address.Should().Be(0x1234); result.Size.Should().Be(100); result.Gen.Should().Be(2); result.FullTypeName.Should().Be("System.String"); result.Value.Should().Be("Duke the corgi"); }
/// <summary>VerifyRedirect</summary> /// <param name="queryString">string</param> /// <param name="dsRSAwithSHA1">DigitalSign</param> /// <returns>bool</returns> public static bool VerifyRedirect(string queryString, DigitalSign dsRSAwithSHA1) { // EcodeRedirectの逆 // Signatureの抽出 string signature = StringExtractor.GetParameterFromQueryString("Signature", queryString); // Signatureの削除 queryString = queryString.Replace("&Signature=" + signature, ""); // queryString : ASCIIデコード // signature : パラメタ → URLデコード → Base64デコード if (dsRSAwithSHA1.Verify( CustomEncode.StringToByte(queryString, CustomEncode.us_ascii), CustomEncode.FromBase64String(CustomEncode.UrlDecode(signature)))) { // 署名検証 OK return(true); } else { // 署名検証 NG return(false); } }
public void MethodNeedsLocalization_Uses_NoLocalizableStringsPresentAttribute_Test() { var testPlatformType = typeof(TestPlatformSkipping); var skipOnWindows = testPlatformType.GetMethod("SkipOnWindows"); var skipOnWindowsAndLinux = testPlatformType.GetMethod("SkipOnWindowsAndLinux"); var skipOnLinux = testPlatformType.GetMethod("SkipOnLinux"); var skipOnAll = testPlatformType.GetMethod("SkipOnAll"); var skipOnNone = testPlatformType.GetMethod("SkipOnNone"); // Test that the attribute behaves properly on all currently tested platforms Assert.That(StringExtractor.MethodNeedsLocalization(skipOnAll), Is.False, "NoLocalizableStrings without argument is not working"); Assert.That(StringExtractor.MethodNeedsLocalization(skipOnNone), Is.True, "A method without NoLocalizableStrings should be localized"); if (Environment.OSVersion.Platform == PlatformID.Unix) { Assert.That(StringExtractor.MethodNeedsLocalization(skipOnWindows), Is.True, "NoLocalizableStrings for Windows should localize on linux"); Assert.That(StringExtractor.MethodNeedsLocalization(skipOnWindowsAndLinux), Is.False, "Should not be localized on linux"); Assert.That(StringExtractor.MethodNeedsLocalization(skipOnLinux), Is.False, "Should not be localized on linux"); } else if (Environment.OSVersion.Platform == PlatformID.Win32NT) { Assert.That(StringExtractor.MethodNeedsLocalization(skipOnWindows), Is.False, "Should not be localized on Windows"); Assert.That(StringExtractor.MethodNeedsLocalization(skipOnWindowsAndLinux), Is.False, "Should not be localized on Windows"); Assert.That(StringExtractor.MethodNeedsLocalization(skipOnLinux), Is.True, "NoLocalizableStrings for Linux should localize on Windows"); } }
public void EscapedQuoteTest() { string source = @"Foo eq 'B\'ar'"; var target = new StringExtractor(source); Assert.AreEqual("Foo eq ?0", target.ModifedString); Assert.AreEqual(@"B'ar", target.GetValue("?0")); }
public void NothingButEscapedQuotesTest() { string source = @"Foo eq '\'\'\'\''"; var target = new StringExtractor(source); Assert.AreEqual("Foo eq ?0", target.ModifedString); Assert.AreEqual(@"''''", target.GetValue("?0")); }
public void SingleStringTest() { string source = @"Foo eq 'Bar'"; var target = new StringExtractor(source); Assert.AreEqual("Foo eq ?0", target.ModifedString); Assert.AreEqual("Bar", target.GetValue("?0")); }
public void FindLocalizedStringsInType_RequestNamespaceForSubclass_DoNotExtractStringsForSuperclassWithDifferentNamespace() { var stringExtractor = new StringExtractor(); var localizedStrings = stringExtractor.DoExtractingWork(new[] { "L10NSharp.TestsWithDifferentNamespace" }, new BackgroundWorker { WorkerReportsProgress = true }); Assert.AreEqual(0, localizedStrings.Count()); }
public void TwoStringsTest() { string source = @"Foo eq 'Bar' and Quux eq 'Wibble'"; var target = new StringExtractor(source); Assert.AreEqual("Foo eq ?0 and Quux eq ?1", target.ModifedString); Assert.AreEqual("Bar", target.GetValue("?0")); Assert.AreEqual("Wibble", target.GetValue("?1")); }
static void Main(string[] args) { // Parse and check the command line arguments. if (!ParseOptions(args)) { Usage(); return; } LocalizationManager.TranslationMemoryKind = TranslationMemory.XLiff; // Load the input assemblies so that they can be scanned. List <Assembly> assemblies = new List <Assembly>(); foreach (var file in _assemblyFiles) { var asm = Assembly.LoadFile(file); if (asm != null) { assemblies.Add(asm); } } // Scan the input assemblies for localizable strings. var extractor = new StringExtractor <XLiffDocument> { ExternalAssembliesToScan = assemblies.ToArray() }; var localizedStrings = extractor.DoExtractingWork(_namespaces.ToArray(), null); // The arguments to this constructor don't really matter much as they're used internally by // L10NSharp for reasons that may not percolate out to xliff. We just need a LocalizationManagerInternal // to feed into the constructor the LocalizedStringCache that does some heavy lifting for us in // creating the XliffDocument from the newly extracted localized strings. var lm = new XLiffLocalizationManager(_fileOriginal, _fileOriginal, _fileProductVersion); var stringCache = new XLiffLocalizedStringCache(lm, false); foreach (var locInfo in localizedStrings) { stringCache.UpdateLocalizedInfo(locInfo); } // Get the newly loaded static strings (in newDoc) and the baseline XLIFF (in baseDoc). var newDoc = stringCache.XliffDocuments[kDefaultLangId]; var baseDoc = LoadBaselineAndCompare(newDoc); // Save the results to the output file, merging in data from the baseline XLIFF if one was specified. var xliffOutput = XLiffLocalizationManager.MergeXliffDocuments(newDoc, baseDoc, _verbose); xliffOutput.File.SourceLang = kDefaultLangId; xliffOutput.File.ProductVersion = !string.IsNullOrEmpty(_fileProductVersion) ? _fileProductVersion : newDoc.File.ProductVersion; xliffOutput.File.HardLineBreakReplacement = kDefaultNewlineReplacement; xliffOutput.File.AmpersandReplacement = kDefaultAmpersandReplacement; xliffOutput.File.Original = _fileOriginal; xliffOutput.File.DataType = !string.IsNullOrEmpty(_fileDatatype) ? _fileDatatype : newDoc.File.DataType; xliffOutput.Save(_xliffOutputFilename); }
public void CorruptedNoEnd() { var instance = new StringExtractor("12", "345"); var text = "qwert12asdzxc"; var result = instance.Extract(text); Assert.AreEqual(0, result.Length); }
public TV(string URL) { SeriesName = StringExtractor.getBetween(URL, "<span itemprop=\"name\">", "</span>"); Season = StringExtractor.getBetween(URL, "class=\"ep_season\" itemprop=\"partOfSeason\">Season ", "<"); EpisodeNumber = StringExtractor.getBetween(URL, "<span class=\"ep_number\">Episode <span itemprop=\"number\">", "<"); EpisodeName = StringExtractor.getBetween(URL, "<h2 class=\"ep_title\" itemprop=\"name\">", "<"); }
public void RealCase() { var instance = new StringExtractor("@R(\"", "\""); var text = "< a rel = \"nofollow\" href = \"@Url.Action(\"history\", \"Resource\", new { id = Model.Id, title = Model.Title.NormalizeFormat(true), area = string.Empty })\" id = \"history\" > @R(\"Show history\") </ a > "; var result = instance.Extract(text); Assert.AreEqual(1, result.Length); Assert.AreEqual("Show history", result[0]); }
public void Scenario1() { var instance = new StringExtractor("12", "345"); var text = "qwert12asd345zxc"; var result = instance.Extract(text); Assert.AreEqual(1, result.Length); Assert.AreEqual("asd", result[0]); }
public WordCloudForm(string text) { InitializeComponent(); IProgressIndicator progress = new ProgressBarWrapper(progressBar1); IEnumerable <string> terms = new StringExtractor(text, progress); cloudControl.WeightedWords = terms.CountOccurences().SortByOccurences(); progressBar1.Hide(); }
public IMDB(string URL) { Holder = StringExtractor.getBetween(URL, "<div class=\"titleParent\">", "</div>"); SeriesName = StringExtractor.getBetween(Holder, "title=\"", "\" >"); Holder = StringExtractor.getBetween(URL, "<div class=\"bp_heading\">", "div>"); Season = StringExtractor.getBetween(Holder, "Season ", "<"); EpisodeNumber = StringExtractor.getBetween(Holder, "Episode", "<"); EpisodeName = StringExtractor.getBetween(URL, "<h1 itemprop=\"name\" class=\"\">", " "); }
/// <summary>XML宣言のエンコーディングを返す</summary> /// <param name="xmlDeclaration">string</param> /// <returns>Encoding</returns> public static Encoding GetEncodingFromXmlDeclaration(string xmlDeclaration) { try { // エンコーディング オブジェクトに変換 return(Encoding.GetEncoding( StringExtractor.GetAttributeFromXml(xmlDeclaration, "encoding"))); } catch (Exception) { // ここでエラーとなった場合、 throw new ArgumentException(String.Format( PublicExceptionMessage.XML_DECLARATION_ERROR, xmlDeclaration)); } }
private void UpdateWords() { if (inputText.Length < 3) { return; } IEnumerable <string> terms = new StringExtractor(inputText, _progress); CloudControl.WeightedWords = terms .Filter(_blacklist) .CountOccurences() .SortByOccurences(); }
public void Indicate_It_Can_Extract_Only_Strings() { // arrange var extractor = new StringExtractor(); var stringBuilder = new ClrObjectBuilder(); stringBuilder.WithType("System.String"); var s = stringBuilder.Build(); var builder = new ClrObjectBuilder(); builder.WithType("System.Object"); var o = builder.Build(); // act // assert extractor.CanExtract(s, null).Should().BeTrue(); extractor.CanExtract(o, null).Should().BeFalse(); }
private void cmbSelectWindow_SelectedIndexChanged(object sender, EventArgs e) { if (cmbSelectWindow.SelectedIndex != 0 && selectWindowReady) { IProgressIndicator progress = new ProgressBarWrapper(progressBar); string timeSlotID = cmbSelectWindow.SelectedValue.ToString(); SingleWindow sw = _slidingWindows.GetWindow(timeSlotID); IEnumerable <string> terms = new StringExtractor(Util.GenerateText(sw.CandidateTopics).ToString(), progress); myCloudControl.WeightedWords = terms .CountOccurences() .SortByOccurences(); progressBar.Visible = false; pnlWordCloud.Visible = true; rTxtResults.Visible = false; } }
public static void Main() { SubsequenceGetter subsequenceGetter = new SubsequenceGetter(); var substr = subsequenceGetter.GetSubsequence("Hello!".ToCharArray(), 2, 3); Console.WriteLine(substr); var subarr = subsequenceGetter.GetSubsequence(new int[] { -1, 3, 2, 1 }, 0, 2); Console.WriteLine(string.Join(" ", subarr)); var allarr = subsequenceGetter.GetSubsequence(new int[] { -1, 3, 2, 1 }, 0, 4); Console.WriteLine(string.Join(" ", allarr)); var emptyarr = subsequenceGetter.GetSubsequence(new int[] { -1, 3, 2, 1 }, 0, 0); Console.WriteLine(string.Join(" ", emptyarr)); StringExtractor stringExtractor = new StringExtractor(); Console.WriteLine(stringExtractor.ExtractEnding("I love C#", 2)); Console.WriteLine(stringExtractor.ExtractEnding("Nakov", 4)); Console.WriteLine(stringExtractor.ExtractEnding("beer", 4)); Console.WriteLine(stringExtractor.ExtractEnding("Hi", 100)); PrintIsPrime(23); PrintIsPrime(33); List<Exam> peterExams = new List<Exam>() { new SimpleMathExam(2), new CSharpExam(55), new CSharpExam(100), new SimpleMathExam(1), new CSharpExam(0), }; Student peter = new Student("Peter", "Petrov", peterExams); double peterAverageResult = peter.CalcAverageExamResultInPercents(); Console.WriteLine("Average results = {0:p0}", peterAverageResult); }
//-------------------------------------------------------------------------- // Construction public ExtractedSequence(DistillationContext context, SymbolTable symtab, INucleotideSequence target, int intFirst, int cnt) : base(context, symtab, target) { this.id = EnumeratedNucleotideSequence.NewId(); // StringExtractor.Confine(0, target.Length, ref intFirst, ref cnt); // note, though: target's length can change this.stringExtractor = new StringExtractor(intFirst, cnt); // this.isOurDecoration = dec => { if (dec.Ich >= this.stringExtractor.IchFirst && dec.Ich < this.stringExtractor.IchMax) return true; if (this.stringExtractor.IchFirst == 0 && dec.Ich < 0) return true; if (this.stringExtractor.IchMax >= this.target.Length && dec.Ich == this.target.Length) return true; return false; }; }
static void Main(string[] args) { // Parse and check the command line arguments. if (!ParseOptions(args)) { Usage(); return; } LocalizationManager.TranslationMemoryKind = TranslationMemory.XLiff; // Load the input assemblies so that they can be scanned. List <Assembly> assemblies = new List <Assembly>(); List <string> assemblyPaths = new List <string>(); if (_glob) { foreach (var glob in _assemblyFiles) { assemblyPaths.AddRange(Directory.GetFiles(Path.GetDirectoryName(glob), Path.GetFileName(glob))); } } else { assemblyPaths = _assemblyFiles; } foreach (var file in assemblyPaths) { // Using LoadFrom to make sure we pick up other assemblies in the same directory so we don't fail // to load because of 'missing' dependencies var asm = Assembly.LoadFrom(file); assemblies.Add(asm); for (var index = 0; index < _additionalLocalizationMethodNames.Count; index++) { var methodNameSpec = _additionalLocalizationMethodNames[index]; try { var type = asm.GetType(methodNameSpec.Item1 + "." + methodNameSpec.Item2); if (type == null) { continue; } _additionalLocalizationMethods.AddRange(type .GetMethods(BindingFlags.Static | BindingFlags.Public) .Where(m => m.Name == methodNameSpec.Item3)); if (_verbose) { Console.WriteLine($"Method {methodNameSpec.Item2}.{methodNameSpec.Item3} in {asm.GetName().FullName} will be treated as a localization method."); } _additionalLocalizationMethodNames.RemoveAt(index--); } catch (Exception e) { if (_verbose) { Console.WriteLine("Error using reflection on {asm.GetName().FullName} to get type {methodNameSpec.Item2} or method {methodNameSpec.Item3}:" + e.Message); } } } } if (_verbose && _additionalLocalizationMethodNames.Any()) { Console.WriteLine("Failed to find the following additional localization methods:"); foreach (var methodNameSpec in _additionalLocalizationMethodNames) { Console.WriteLine($"{methodNameSpec.Item1}.{methodNameSpec.Item2}.{methodNameSpec.Item3}"); } } // Scan the input assemblies for localizable strings. var extractor = new StringExtractor <XLiffDocument> { ExternalAssembliesToScan = assemblies.ToArray() }; extractor.OutputErrorsToConsole = _verbose; var localizedStrings = extractor.DoExtractingWork(_additionalLocalizationMethods, _namespaces.ToArray(), null); // The arguments to this constructor don't really matter much as they're used internally by // L10NSharp for reasons that may not percolate out to xliff. We just need a LocalizationManagerInternal // to feed into the constructor the LocalizedStringCache that does some heavy lifting for us in // creating the XliffDocument from the newly extracted localized strings. var lm = new XLiffLocalizationManager(_fileOriginal, _fileOriginal, _fileProductVersion); var stringCache = new XLiffLocalizedStringCache(lm, false); foreach (var locInfo in localizedStrings) { stringCache.UpdateLocalizedInfo(locInfo); } // Get the newly loaded static strings (in newDoc) and the baseline XLIFF (in baseDoc). var newDoc = stringCache.GetDocument(kDefaultLangId); var baseDoc = LoadBaselineAndCompare(newDoc); // Save the results to the output file, merging in data from the baseline XLIFF if one was specified. var xliffOutput = XLiffLocalizationManager.MergeXliffDocuments(newDoc, baseDoc, _verbose); xliffOutput.File.SourceLang = kDefaultLangId; xliffOutput.File.ProductVersion = !string.IsNullOrEmpty(_fileProductVersion) ? _fileProductVersion : newDoc.File.ProductVersion; xliffOutput.File.HardLineBreakReplacement = kDefaultNewlineReplacement; xliffOutput.File.AmpersandReplacement = kDefaultAmpersandReplacement; xliffOutput.File.Original = _fileOriginal; xliffOutput.File.DataType = !string.IsNullOrEmpty(_fileDatatype) ? _fileDatatype : newDoc.File.DataType; xliffOutput.Save(_xliffOutputFilename); }
private void ExtractStringList() { const string _File = "file"; const string _Line = "line"; const string _Col = "col"; const string _Type = "type"; const string _String = "string"; Dictionary <string, string> defaultColumns = new Dictionary <string, string> { [_File] = "File", [_Line] = "Line", [_Col] = "Col", [_Type] = "Type", [_String] = "String", }; string schema_name = cmd.GetValue("schema-name") ?? SchemaName.dbo; string table_name = cmd.GetValue("table-name"); bool allDirectories = cmd.Has("subdirectory"); string[] file_names = cmd.InputFiles(allDirectories); string[] excludes = cmd.Excludes; IDictionary <string, string> column_names = cmd.GetDictionary("column-names", defaultColumns); if (file_names == null) { cerr.WriteLine($"file name or directory is not defined, use option /in:file_name"); return; } if (file_names.Length == 0) { cerr.WriteLine($"file doesn't exist: \"{file_names}\""); return; } if (tname == null) { if (table_name == null) { cerr.WriteLine($"/table-name is not defined"); return; } if (dname == null) { cerr.WriteLine($"required to select a database"); return; } tname = new TableName(dname, schema_name, table_name); if (!tname.Exists()) { cerr.WriteLine($"table-name doesn't exist: {tname}"); return; } } DataTable dt = new TableReader(tname) { CaseSensitive = true, }.Table; StringDumper dumper = new StringDumper(tname) { Line = column_names[_Line], Column = column_names[_Col], Type = column_names[_Type], FileName = column_names[_File], Value = column_names[_String], }; dumper.Initialize(); StringExtractor extractor = new StringExtractor(dumper); if (!ValidateColumn <int>(dt, dumper.Line, "column-name", required: true)) { return; } if (!ValidateColumn <int>(dt, dumper.Column, "column-name", required: true)) { return; } if (!ValidateColumn <string>(dt, dumper.FileName, "column-name", required: false)) { return; } if (!ValidateColumn <string>(dt, dumper.Type, "column-name", required: false)) { return; } if (!ValidateColumn <string>(dt, dumper.Value, "column-name", required: false)) { return; } foreach (string file in file_names) { if (file.IsMatch(excludes)) { Console.WriteLine($"skip: {file}"); continue; } if (file.EndsWith("AssemblyInfo.cs")) { continue; } int count = extractor.Extract(file); if (count > 0) { cout.WriteLine($"{count} of strings were extracted in file: \"{file}\""); } else { cout.WriteLine($"no string found in file: \"{file}\""); } } bool commit = cmd.Has("submit-changes"); if (!commit) { return; } cout.WriteLine($"starting to save changes into table \"{tname}\""); try { TableWriter tableWriter = new TableWriter(tname); tableWriter.Save(dumper.Table); cout.WriteLine($"completed to save on table \"{tname}\" from \"{cmd.InputPath()}\""); } catch (Exception ex) { cerr.WriteLine($"failed to save in \"{tname}\" , {ex.AllMessages()}"); } }
protected override void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { var extractor = new StringExtractor <T>(); e.Result = extractor.DoExtractingWork(_namespaceBeginnings, sender as BackgroundWorker); }
public string SiteDetector(string URL) { return(StringExtractor.getBetween(URL, "www.", ".com")); }