private static string SetJson(SetRecord record, int indent, bool ignoreFirstIndent) { StringBuilder builder = new StringBuilder(capacity: record.Count * 64); if (ignoreFirstIndent == false) { builder.AppendIndent(indent); } builder.Append('{'); int indentPlus = indent + 1; int indentPPlus = indentPlus + 1; foreach (var pair in record) { builder.AppendLine(); builder.AppendIndent(indentPlus); builder.AppendFormat("\"{0}\": {1}", pair.Key, Json(pair.Value, indentPlus, true)); builder.Append(','); } if (builder.Length > 0) { builder.Remove(builder.Length - 1, 1); } builder.AppendLine(); builder.AppendIndent(indent); builder.Append('}'); return(builder.ToString()); }
public static BookmarkCollection Retrive() { string appdata = Environment.GetEnvironmentVariable("appdata"); string filepath = Path.Combine(appdata, @"..\local\Google\Chrome\User Data\Default\Bookmarks"); if (!File.Exists(filepath)) { return(CreateEmpty()); } Stream stream = File.OpenRead(filepath); SetRecord record = Hake.Extension.ValueRecord.Json.Converter.ReadJson(stream) as SetRecord; stream.Dispose(); if (record == null) { return(CreateEmpty()); } SetRecord bookmarkbar = record.FromPath("roots.bookmark_bar") as SetRecord; SetRecord others = record.FromPath("roots.other") as SetRecord; return(new BookmarkCollection() { BookmarkBar = RetriveFolder(bookmarkbar), Others = RetriveFolder(others) }); }
public ConfigurationBuilder AddDefault() { Assembly ass = Assembly.GetEntryAssembly(); Stream stream = ass.LoadStream("HakeQuick.default.json"); RecordBase record = Converter.ReadJson(stream); stream.Dispose(); if (record is SetRecord set) { if (values == null) { values = set; } else { values.Combine(set); } } else { throw new Exception("invalid configuration format"); } return(this); }
private static BookmarkFolder RetriveFolder(SetRecord record) { string name = record.ReadAs <string>("name"); string type; ListRecord children = record["children"] as ListRecord; List <Bookmark> bookmarks = new List <Bookmark>(); List <BookmarkFolder> folders = new List <BookmarkFolder>(); foreach (RecordBase rec in children) { if (rec is SetRecord set) { type = set.ReadAs <string>("type"); if (type == "folder") { folders.Add(RetriveFolder(set)); } else if (type == "url") { bookmarks.Add(RetriveBookmark(set)); } } } return(new BookmarkFolder() { Name = name, Bookmarks = bookmarks, Folders = folders }); }
private static Bookmark RetriveBookmark(SetRecord record) { string name = record.ReadAs <string>("name"); ChineseChar ch; StringBuilder builder = new StringBuilder(name.Length); foreach (char c in name) { if (ChineseChar.IsValidChar(c)) { ch = new ChineseChar(c); builder.Append(ch.Pinyins[0]); builder.Remove(builder.Length - 1, 1); } else { builder.Append(c); } } string pinyin = builder.ToString().ToLower(); return(new Bookmark() { Name = name, Url = record.ReadAs <string>("url"), NamePinYin = pinyin }); }
public static SetRecord Combine(this SetRecord dest, SetRecord source) { if (dest == null) { throw new ArgumentNullException(nameof(dest)); } if (source == null) { throw new ArgumentNullException(nameof(source)); } RecordBase temp; foreach (var pair in source) { if (dest.TryGetValue(pair.Key, out temp)) { if (pair.Value is SetRecord srcset && temp is SetRecord dstset) { Combine(dstset, srcset); } else { dest[pair.Key] = pair.Value; } }
public void TestCsSetToCppSet() { var sSet = new HashSet <string> { "StringA", "StringB", "StringC" }; var iSet = new HashSet <int>(); var setRecord = new SetRecord(sSet, iSet); Assert.That(() => TestHelpers.CheckSetRecord(setRecord), Is.True); }
public static IConfiguartion Read(SetRecord set) { if (set == null) { throw new ArgumentNullException(nameof(set)); } RecordBase record; SetRecord setIncludeItems = null; SetRecord setGlobalExcludes = null; ListRecord setScanDirectories = null; if (set.TryGetValue("scan", out record)) { setScanDirectories = record as ListRecord; } if (set.TryGetValue("include", out record)) { setIncludeItems = record as SetRecord; } if (set.TryGetValue("exclude", out record)) { setGlobalExcludes = record as SetRecord; } ItemIncludeOptions resultInclude = ReadItemIncludeOptions(setIncludeItems); ScanFilterOptions resultExclude = null; if (setGlobalExcludes == null) { resultExclude = ScanFilterOptions.CreateExcludeDefault(); } else { resultExclude = ReadFilterOptions(setGlobalExcludes); } List <DirectoryScanOptions> resultScanDirectories = new List <DirectoryScanOptions>(); if (setScanDirectories != null) { foreach (RecordBase scanOptions in setScanDirectories) { if (scanOptions is SetRecord setScanOptions) { resultScanDirectories.Add(ReadDirectoryScanOptions(resultExclude, setScanOptions)); } } } return(new Configuration(resultExclude, resultInclude, resultScanDirectories)); }
public string Get(HttpContext httpContext, string code, string defaultName, ICultureExpression requestedCulture) { string culture = requestedCulture.DisplayName; CulturePage culturePage = cultureCache.Get(culture, key => { string basePath = matchingOption.ResourceDirectory; IList <IFileCultureInfo> files = ResourceRequestHelper.FindFiles(basePath, "json", requestedCulture, httpContext); if (files.Count <= 0) { files = ResourceRequestHelper.FindFiles(basePath, "json", cultureOption.DefaultCulture, httpContext); } if (files.Count <= 0) { return(RetrivationResult <CulturePage> .Create(new EmptyCulturePage())); } string filePath; IHostingEnvironment env = httpContext.RequestServices.GetRequiredService <IHostingEnvironment>(); IFileProvider provider = env.ContentRootFileProvider; SetRecord values = new SetRecord(); foreach (IFileCultureInfo file in files.Reverse()) { filePath = file.RelativePath; IFileInfo current = provider.GetFileInfo(filePath); try { using (Stream fileStream = current.CreateReadStream()) { SetRecord fileContent = (SetRecord)Hake.Extension.ValueRecord.Json.Converter.ReadJson(fileStream, !matchingOption.IsCaseSensitive); CombineSetRecord(values, fileContent); } } catch { } } return(RetrivationResult <CulturePage> .Create(new CulturePage(perCultureCapacity, values))); }); return(culturePage.ContentCache.Get(code, key => { if (culturePage.Values.TryReadAs <string>($"{key}.name", out string value) && value != null) { return RetrivationResult <string> .Create(value); } return RetrivationResult <string> .SupressResult(defaultName); })); }
internal static WordResult FromRecord(SetRecord record) { if (record == null) { throw new ArgumentNullException(nameof(record)); } if (record.TryGetValue("word", out RecordBase wordRecord) && wordRecord is ScalerRecord wordScaler) { if (wordScaler.ScalerType == ScalerType.Null) { return(null); } string word = wordScaler.ReadAs <string>().Trim(); WordPronunciationsCollection pronunciationCollection = null; if (record.TryGetValue("pronunciation", out RecordBase pronunciation)) { pronunciationCollection = WordPronunciationsCollection.FromRecord(pronunciation as SetRecord); } else { pronunciationCollection = WordPronunciationsCollection.FromRecord(null); } WordDefinitionsCollection definitionCollection = null; if (record.TryGetValue("defs", out RecordBase defs)) { definitionCollection = WordDefinitionsCollection.FromRecord(defs as ListRecord); } else { definitionCollection = WordDefinitionsCollection.FromRecord(null); } SentencesCollection sentencesCollection = null; if (record.TryGetValue("sams", out RecordBase sentences)) { sentencesCollection = SentencesCollection.FromRecord(sentences as ListRecord); } else { sentencesCollection = SentencesCollection.FromRecord(null); } return(new WordResult(word, pronunciationCollection, definitionCollection, sentencesCollection)); } else { throw new Exception($"can not read {nameof(WordResult)} from record"); } }
private static ItemIncludeOptions ReadItemIncludeOptions(SetRecord set) { List <string> resultDirectories = new List <string>(); List <string> resultFiles = new List <string>(); // return empty list if null if (set == null) { return(new ItemIncludeOptions(resultDirectories, resultFiles)); } RecordBase record; ListRecord directories = null; ListRecord files = null; if (set.TryGetValue("directories", out record)) { directories = record as ListRecord; } if (set.TryGetValue("files", out record)) { files = record as ListRecord; } if (directories != null) { foreach (RecordBase rec in directories) { if (rec is ScalerRecord scaler && scaler.ScalerType == ScalerType.String) { resultDirectories.Add(scaler.ReadAs <string>()); } } } if (files != null) { foreach (RecordBase rec in files) { if (rec is ScalerRecord scaler && scaler.ScalerType == ScalerType.String) { resultFiles.Add(scaler.ReadAs <string>()); } } } return(new ItemIncludeOptions(resultDirectories, resultFiles)); }
public static void Initialize(ICurrentEnvironment env) { Stream defaultConfigStream = Assembly.GetExecutingAssembly().LoadStream("Chrome.BookmarkSearch.default.json"); SetRecord defaultConfig = Converter.ReadJson(defaultConfigStream) as SetRecord; string configPath = env.ConfigDirectory + "\\bookmarksearch.json"; if (File.Exists(configPath)) { try { Stream userConfigStream = File.OpenRead(configPath); SetRecord userConfig = Converter.ReadJson(userConfigStream) as SetRecord; userConfigStream.Dispose(); defaultConfig.Combine(userConfig); } catch { } } else { try { defaultConfigStream.Seek(0, SeekOrigin.Begin); FileStream configStream = File.Create(configPath); defaultConfigStream.CopyTo(configStream); configStream.Flush(); configStream.Dispose(); } catch { } } defaultConfigStream.Dispose(); ConfigurationRecord = defaultConfig; Config = new SearchConfig() { SearchUrl = ConfigurationRecord.ReadAs <bool>("allow_url_search"), EnableSearch = ConfigurationRecord.ReadAs <bool>("enable") }; Bookmarks = BookmarkCollection.Retrive(); SearchPatternErrorAction = new ErrorAction(null, "搜索模式错误", "搜索模式错误"); }
public void RenewNotification() { lock (locker) { this.notifications.Clear(); Stream fileStream = File.OpenRead(filePath); SetRecord record = (SetRecord)Hake.Extension.ValueRecord.Json.Converter.ReadJson(fileStream); fileStream.Dispose(); foreach (var pair in record) { if (pair.Value is ScalerRecord scaler) { notifications.Add(pair.Key, scaler.ReadAs <string>()); } } } }
public SetRecord CreateOrUpdateSetRecord(SetRecord setRecord) { using (var db = new WorkoutDb()) { if (db.SetRecords.Any(x => x.SetRecordId == setRecord.SetRecordId)) { db.Update(setRecord); } else { db.Add(setRecord); } db.SaveChanges(); return(setRecord); } }
internal static WordPronunciationsCollection FromRecord(SetRecord set) { if (set == null) { return(new WordPronunciationsCollection(null, null)); } WordPronunciation us = null; if (set.TryGetValue("AmE", out RecordBase ameRecord) && ameRecord is ScalerRecord ameScaler && set.TryGetValue("AmEmp3", out RecordBase ameMp3Record) && ameMp3Record is ScalerRecord ameMp3Scaler) { string ame = ameScaler.ReadAs <string>(); if (ameMp3Scaler.ScalerType == ScalerType.Null) { us = new WordPronunciation(ame, null); } else { string uri = ameMp3Scaler.ReadAs <string>(); us = new WordPronunciation(ame, new Uri(uri, UriKind.Absolute)); } } WordPronunciation uk = null; if (set.TryGetValue("BrE", out RecordBase breRecord) && breRecord is ScalerRecord breScaler && set.TryGetValue("BrEmp3", out RecordBase breMp3Record) && breMp3Record is ScalerRecord breMp3Scaler) { string bre = breScaler.ReadAs <string>(); if (breMp3Scaler.ScalerType == ScalerType.Null) { uk = new WordPronunciation(bre, null); } else { string uri = breMp3Scaler.ReadAs <string>(); uk = new WordPronunciation(bre, new Uri(uri, UriKind.Absolute)); } } return(new WordPronunciationsCollection(us, uk)); }
public void SetNotification(string notification, string culture) { lock (locker) { notifications[culture] = notification; SetRecord record = new SetRecord(); foreach (var pair in notifications) { record.Add(pair.Key, new ScalerRecord(pair.Value)); } string json = Hake.Extension.ValueRecord.Json.Converter.Json(record); FileStream stream = File.OpenWrite(filePath); stream.SetLength(0); StreamWriter writer = new StreamWriter(stream); writer.Write(json); writer.Flush(); stream.Flush(); writer.Dispose(); stream.Dispose(); } }
private static void CombineSetRecord(SetRecord destination, SetRecord source) { string key; RecordBase value; RecordBase destValue; foreach (var pair in source) { key = pair.Key; value = pair.Value; if (destination.TryGetValue(key, out destValue)) { if (value is SetRecord sourceSet && destValue is SetRecord destSet) { CombineSetRecord(destSet, sourceSet); } else if (value is ListRecord sourceList && destValue is ListRecord destList) { foreach (RecordBase sourceListElement in sourceList) { destList.Add(sourceListElement); } }
public ConfigurationBuilder AddJson(string file) { Stream stream = File.OpenRead(file); RecordBase record = Converter.ReadJson(stream); stream.Dispose(); if (record is SetRecord set) { if (values == null) { values = set; } else { values.Combine(set); } } else { throw new Exception("invalid configuration format"); } return(this); }
private static DirectoryScanOptions ReadDirectoryScanOptions(ScanFilterOptions globalExcludes, SetRecord set) { if (set == null) { return(null); } if (!set.TryGetValue("path", out RecordBase pathRecord) || !set.TryGetValue("depth", out RecordBase depthRecord)) { return(null); } if (!(pathRecord is ScalerRecord pathScaler) || !(depthRecord is ScalerRecord depthScaler)) { return(null); } if (!pathScaler.TryReadAs(out string path) || !depthScaler.TryReadAs(out int depth)) { return(null); } if (depth <= 0) { depth = 1; } ScanFilterOptions includeOptions; ScanFilterOptions excludeOptions; if (set.TryGetValue("include", out RecordBase includeRecordBase) && includeRecordBase is SetRecord includeRecord) { includeOptions = ReadFilterOptions(includeRecord); } else { includeOptions = ScanFilterOptions.CreateIncludeDefault(); } if (set.TryGetValue("exclude", out RecordBase excludeRecordBase) && excludeRecordBase is SetRecord excludeRecord) { excludeOptions = ReadFilterOptions(excludeRecord); } else { excludeOptions = ScanFilterOptions.CreateExcludeDefault(); } bool ignoreGlobalExclude = false; if (set.TryGetValue("ignoreGlobalExclude", out RecordBase ignoreGlobalExcludeBase) && ignoreGlobalExcludeBase is ScalerRecord ignoreGlobalExcludeScaler && ignoreGlobalExcludeScaler.TryReadAs <bool>(out bool ignoreGlobalExcludeValue)) { ignoreGlobalExclude = ignoreGlobalExcludeValue; } if (!ignoreGlobalExclude) { excludeOptions.Combine(globalExcludes); } return(new DirectoryScanOptions(path, depth, includeOptions, excludeOptions)); }
public static RecordBase ToRecord(object input, bool ignoreKeyCase = false) { if (input == null) { return(new ScalerRecord(null)); } Type valueType = input.GetType(); #if NETSTANDARD1_2 TypeInfo valueTypeInfo = valueType.GetTypeInfo(); #endif #if NETSTANDARD2_0 || NET452 if (valueType.IsEnum) #else if (valueTypeInfo.IsEnum) #endif { string typeName = $"{valueType.Namespace}.{valueType.Name}"; string writeValue = $"{typeName}.{input}"; return(new ScalerRecord(writeValue)); } #if NETSTANDARD2_0 || NET452 if (valueType.IsPrimitive) #else if (valueTypeInfo.IsPrimitive) #endif { return(new ScalerRecord(input)); } if (valueType.Name == "String" && valueType.Namespace == "System") { return(new ScalerRecord(input)); } #if NETSTANDARD2_0 || NET452 Type ienumType = valueType.GetInterface("System.Collections.IEnumerable"); #else Type ienumType = valueTypeInfo.ImplementedInterfaces.FirstOrDefault(t => t.FullName == "System.Collections.IEnumerable"); TypeInfo ienumTypeInfo = ienumType == null ? null : ienumType.GetTypeInfo(); #endif if (ienumType != null) { #if NETSTANDARD2_0 || NET452 MethodInfo getEnumeratorMethod = ienumType.GetMethod("GetEnumerator"); #else MethodInfo getEnumeratorMethod = ienumTypeInfo.DeclaredMethods.FirstOrDefault(m => m.Name == "GetEnumerator"); #endif IEnumerator enumerator = (IEnumerator)getEnumeratorMethod.Invoke(input, null); ListRecord listRecord = new ListRecord(); while (enumerator.MoveNext()) { listRecord.Add(ToRecord(enumerator.Current, ignoreKeyCase)); } return(listRecord); } #if NETSTANDARD2_0 || NET452 if (valueType.IsClass) #else if (valueTypeInfo.IsClass) #endif { #if NETSTANDARD2_0 || NET452 BindingFlags propertyFlags = BindingFlags.Instance; #if PROPERTY_PUBLIC_ONLY propertyFlags |= BindingFlags.Public; PropertyInfo[] properties = valueType.GetProperties(propertyFlags); #endif #else PropertyInfo[] properties = valueTypeInfo.DeclaredProperties.ToArray(); #endif SetRecord setRecord = new SetRecord(ignoreKeyCase); MapPropertyAttribute mapPropertyAttribute; MethodInfo getMethod; string propertyName; object propertyValue; foreach (PropertyInfo property in properties) { getMethod = property.GetMethod; if (getMethod == null) { continue; } mapPropertyAttribute = property.GetCustomAttribute <MapPropertyAttribute>(); if (mapPropertyAttribute == null) { continue; } propertyName = GetNameOrDefault(property, mapPropertyAttribute); propertyValue = getMethod.Invoke(input, null); if (mapPropertyAttribute.ConverterType == null) { setRecord.Add(propertyName, ToRecord(propertyValue, ignoreKeyCase)); } else { #if NETSTANDARD2_0 || NET452 MethodInfo convertToScaler = mapPropertyAttribute.ConverterType.GetMethod(nameof(IScalerTargetTypeConverter <string, string> .ConvertToScaler)); #else MethodInfo convertToScaler = mapPropertyAttribute.ConverterType.GetRuntimeMethods().First(method => method.Name == nameof(IScalerTargetTypeConverter <string, string> .ConvertToScaler)); #endif object converterObject = Activator.CreateInstance(mapPropertyAttribute.ConverterType); object scaler = convertToScaler.Invoke(converterObject, new object[] { propertyValue }); setRecord.Add(propertyName, ToRecord(scaler, ignoreKeyCase)); } } return(setRecord); } throw new Exception($"can not map to record of type {valueType.Namespace}.{valueType.Name}"); }
public ConfigurationBuilder ReplaceAll(SetRecord record) { values = record; return(this); }
public CulturePage(int capacity, SetRecord values) { contentCache = new Cache <string, string>(capacity); this.values = values; }
public SetRecord Post([FromBody] SetRecord setRecord) { return(_recordWorkoutService.CreateOrUpdateSetRecord(setRecord)); }
private static ScanFilterOptions ReadFilterOptions(SetRecord set) { if (set == null) { throw new ArgumentNullException(nameof(set)); } string pattern; Regex tempRegex; RecordBase recordbase; ListRecord directories = null; ListRecord files = null; ListRecord common = null; ListRecord paths = null; if (set.TryGetValue("directory", out recordbase)) { directories = recordbase as ListRecord; } if (set.TryGetValue("file", out recordbase)) { files = recordbase as ListRecord; } if (set.TryGetValue("common", out recordbase)) { common = recordbase as ListRecord; } if (set.TryGetValue("path", out recordbase)) { paths = recordbase as ListRecord; } List <Regex> resultDirectories = new List <Regex>(); List <Regex> resultFiles = new List <Regex>(); List <Regex> resultCommon = new List <Regex>(); List <Regex> resultPaths = new List <Regex>(); if (directories != null) { foreach (RecordBase rec in directories) { if (rec is ScalerRecord scaler && scaler.ScalerType == ScalerType.String) { pattern = scaler.ReadAs <string>(); try { tempRegex = new Regex(pattern); resultDirectories.Add(tempRegex); } catch { } } } } if (files != null) { foreach (RecordBase rec in files) { if (rec is ScalerRecord scaler && scaler.ScalerType == ScalerType.String) { pattern = scaler.ReadAs <string>(); try { tempRegex = new Regex(pattern); resultFiles.Add(tempRegex); } catch { } } } } if (common != null) { foreach (RecordBase rec in common) { if (rec is ScalerRecord scaler && scaler.ScalerType == ScalerType.String) { pattern = scaler.ReadAs <string>(); try { tempRegex = new Regex(pattern); resultCommon.Add(tempRegex); } catch { } } } } if (paths != null) { foreach (RecordBase rec in paths) { if (rec is ScalerRecord scaler && scaler.ScalerType == ScalerType.String) { pattern = scaler.ReadAs <string>(); try { tempRegex = new Regex(pattern); resultPaths.Add(tempRegex); } catch { } } } } return(new ScanFilterOptions(resultFiles, resultDirectories, resultCommon, resultPaths)); }
private static SetRecord ReadSet(InternalTextReader reader, bool ignoreKeyCase) { // resolve '{' reader.Read(); SetRecord set = new SetRecord(ignoreKeyCase); char peek; int result; string key = ""; int state = 0; int oldstate = 0; while (true) { result = reader.Peek(); if (result == -1) { if (state == 0) { throw new Exception("'\"' excepted but end of stream reached"); } else if (state == 1) { throw new Exception("':' excepted but end of stream reached"); } else if (state == 2) { throw new Exception("',' or '}' excepted but end of stream reached"); } else { throw new Exception($"unknown state of {state}"); } } peek = (char)result; if (state == 0) { if (peek.IsWhiteSpace()) { reader.Read(); } else if (peek == '"') { key = ReadStringOrThrow(reader); state = 1; } else if (peek == '/') { oldstate = state; reader.Read(); state = 3; } else if (peek == '}') { reader.Read(); break; } else { throw BuildException($"'\"' excepted but '{peek}' scanned", reader); } } else if (state == 1) { if (peek.IsWhiteSpace()) { reader.Read(); } else if (peek == ':') { reader.Read(); RecordBase record = ReadJson(reader, false, ignoreKeyCase); set.Add(key, record); state = 2; } else if (peek == '/') { oldstate = state; reader.Read(); state = 3; } else { throw BuildException($"':' excepted but '{peek}' scanned", reader); } } else if (state == 2) { if (peek.IsWhiteSpace()) { reader.Read(); } else if (peek == '/') { oldstate = state; reader.Read(); state = 3; } else if (peek == ',') { reader.Read(); state = 0; } else if (peek == '}') { reader.Read(); break; } else { throw BuildException($"',' or '}}' excepted but '{peek}' scanned", reader); } } else if (state == 3) { if (peek == '/') { reader.Read(); state = 4; } else { throw BuildException($"'/' excepted but '{peek}' scanned", reader); } } else if (state == 4) { if (peek == '\n') { reader.Read(); state = oldstate; } else { reader.Read(); } } else { throw new Exception($"unknown state of {state}"); } } return(set); }