private static ReadOnlyDictionary <SquareBridgeKey, Bitboard> GenerateSquareBridgeMap() { var resultMap = new Dictionary <SquareBridgeKey, Bitboard>(AllSquares.Count * AllSquares.Count); var allSquares = AllSquares.ToArray(); for (var outerIndex = 0; outerIndex < allSquares.Length; outerIndex++) { var first = allSquares[outerIndex]; for (var innerIndex = outerIndex + 1; innerIndex < allSquares.Length; innerIndex++) { var second = allSquares[innerIndex]; foreach (var ray in AllRays) { var squares = GetMoveSquareArraysByRays(first, ray.AsArray(), MaxSlidingPieceDistance); var index = Array.IndexOf(squares, second); if (index < 0) { continue; } var key = new SquareBridgeKey(first, second); var squareBridge = new Bitboard(squares.Take(index)); resultMap.Add(key, squareBridge); break; } } } return(resultMap.AsReadOnly()); }
public CursorProvider(ModData modData) { var fileSystem = modData.DefaultFileSystem; var sequenceYaml = MiniYaml.Merge(modData.Manifest.Cursors.Select( s => MiniYaml.FromStream(fileSystem.Open(s), s))); var shadowIndex = new int[] { }; var nodesDict = new MiniYaml(null, sequenceYaml).ToDictionary(); if (nodesDict.ContainsKey("ShadowIndex")) { Array.Resize(ref shadowIndex, shadowIndex.Length + 1); Exts.TryParseIntegerInvariant(nodesDict["ShadowIndex"].Value, out shadowIndex[shadowIndex.Length - 1]); } var palettes = new Dictionary<string, ImmutablePalette>(); foreach (var p in nodesDict["Palettes"].Nodes) palettes.Add(p.Key, new ImmutablePalette(fileSystem.Open(p.Value.Value), shadowIndex)); Palettes = palettes.AsReadOnly(); var frameCache = new FrameCache(fileSystem, modData.SpriteLoaders); var cursors = new Dictionary<string, CursorSequence>(); foreach (var s in nodesDict["Cursors"].Nodes) foreach (var sequence in s.Value.Nodes) cursors.Add(sequence.Key, new CursorSequence(frameCache, sequence.Key, s.Key, s.Value.Value, sequence.Value)); Cursors = cursors.AsReadOnly(); }
public InternalResourceManager() { string robotsFile = UnityEngine.Resources.Load <TextAsset>("Package/iviz/resources")?.text; if (string.IsNullOrEmpty(robotsFile)) { Logger.Warn($"{this}: Empty resource file!"); robotDescriptions = new Dictionary <string, string>().AsReadOnly(); return; } Dictionary <string, string> robots = JsonConvert.DeserializeObject <Dictionary <string, string> >(robotsFile); Dictionary <string, string> tmpRobotDescriptions = new Dictionary <string, string>(); foreach (var pair in robots) { string robotDescription = UnityEngine.Resources.Load <TextAsset>("Package/iviz/robots/" + pair.Value)?.text; if (string.IsNullOrEmpty(robotDescription)) { Logger.Info($"{this}: Empty or null description file {pair.Value}!"); continue; } tmpRobotDescriptions[pair.Key] = robotDescription; } robotDescriptions = tmpRobotDescriptions.AsReadOnly(); }
public static Collections.ReadOnlyDictionary <String, List <String> > GetReadOnlyCache() { var cloneCachePath = new Dictionary <String, String>(_cacheUri); if (cloneCachePath.Keys.Count == 0) { return((new Dictionary <string, List <string> >()).AsReadOnly()); } var result = new Dictionary <String, List <String> >(); foreach (var keyValuePair in cloneCachePath) { var category = keyValuePair.Key.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries)[0]; if (!result.ContainsKey(category)) { result.Add(category, new List <String>()); } result[category].Add(keyValuePair.Value); } return(result.AsReadOnly()); }
internal TokenUsedEventArgs(CommandParameterGroupList commandParameterGroupList) { if (commandParameterGroupList == null) throw new ArgumentNullException("commandParameterGroupList"); const string PATTERN = @"ident=(?<ident>[^\s=]+)\s+(?<value>value=.*)"; string customSettingsString = commandParameterGroupList.GetParameterValue("tokencustomset"); Dictionary<string, string> customSettings = new Dictionary<string, string>(); if (!customSettingsString.IsNullOrTrimmedEmpty()) { foreach (string splittedSetting in customSettingsString.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)) { Match match = Regex.Match(splittedSetting, PATTERN, RegexOptions.Singleline | RegexOptions.IgnoreCase); if (!match.Success) continue; customSettings[match.Groups["ident"].Value] = match.Groups["value"].Value; } } ClientId = commandParameterGroupList.GetParameterValue<uint>("clid"); ClientUniqueId = commandParameterGroupList.GetParameterValue("cluid"); ClientDatabaseId = commandParameterGroupList.GetParameterValue<uint>("cldbid"); TokenText = commandParameterGroupList.GetParameterValue("token"); GroupId = commandParameterGroupList.GetParameterValue<uint>("token1"); ChannelId = commandParameterGroupList.GetParameterValue<uint>("token2"); CustomSettings = customSettings.AsReadOnly(); }
internal static IDictionary <string, ISchema> ParseSchemas(JsonDictionary js) { js.ThrowIfNull("values"); RemoveAnnotations(js, 0); var working = new Dictionary <string, ISchema>(); var resolver = new FutureJsonSchemaResolver(); foreach (KeyValuePair <string, object> kvp in js) { logger.Debug("Found schema {0}", kvp.Key); var serilizer = new JsonSerializer(); var textWriter = new StringWriter(); serilizer.Serialize(textWriter, kvp.Value); string result = textWriter.ToString(); ISchema schema = new SchemaImpl(kvp.Key, result, resolver); working.Add(schema.Name, schema); } resolver.ResolveAndVerify(); return(working.AsReadOnly()); }
/// <summary> /// Return a map from visible ids to factories. /// </summary> private IDictionary <string, IServiceFactory> GetVisibleIDMap() { lock (this) { // or idcache-only lock? if (idcache == null) { try { factoryLock.AcquireRead(); IDictionary <string, IServiceFactory> mutableMap = new Dictionary <string, IServiceFactory>(); for (int i = factories.Count - 1; i >= 0; i--) { IServiceFactory f = factories[i]; f.UpdateVisibleIDs(mutableMap); } this.idcache = mutableMap.AsReadOnly(); } finally { factoryLock.ReleaseRead(); } } } return(idcache); }
internal TokenUsedEventArgs(CommandParameterGroupList commandParameterGroupList) { if (commandParameterGroupList == null) { throw new ArgumentNullException(nameof(commandParameterGroupList)); } const string PATTERN = @"ident=(?<ident>[^\s=]+)\s+(?<value>value=.*)"; string customSettingsString = commandParameterGroupList.GetParameterValue("tokencustomset"); Dictionary <string, string> customSettings = new Dictionary <string, string>(); if (!customSettingsString.IsNullOrTrimmedEmpty()) { foreach (string splittedSetting in customSettingsString.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)) { Match match = Regex.Match(splittedSetting, PATTERN, RegexOptions.Singleline | RegexOptions.IgnoreCase); if (!match.Success) { continue; } customSettings[match.Groups["ident"].Value] = match.Groups["value"].Value; } } ClientId = commandParameterGroupList.GetParameterValue <uint>("clid"); ClientUniqueId = commandParameterGroupList.GetParameterValue("cluid"); ClientDatabaseId = commandParameterGroupList.GetParameterValue <uint>("cldbid"); TokenText = commandParameterGroupList.GetParameterValue("token"); GroupId = commandParameterGroupList.GetParameterValue <uint>("token1"); ChannelId = commandParameterGroupList.GetParameterValue <uint>("token2"); CustomSettings = customSettings.AsReadOnly(); }
static IDictionary <byte, IList <byte> > GenerateSp2Map(bool isPsp) { Dictionary <byte, IList <byte> > result = new Dictionary <byte, IList <byte> >(); for (byte index = 0; index < 159; index++) { result.Add(index, new byte[1] { index }); } if (isPsp) { result[0x9A] = new byte[4] { 0xAA, 0xAB, 0xAC, 0xAD }; } else { result[0x9A] = new byte[4] { 0x9F, 0xA0, 0xA1, 0xA2 }; } return(result.AsReadOnly()); }
static HasCustomAttribute() { var d = new Dictionary<MetadataTable, uint>(); for (uint i = 0; i < s_tables.Length; ++i) { d.Add(s_tables[i], i); } s_inverseTables = d.AsReadOnly(); }
private static void EnsureDocumentationDictionaries() { if (_packageProgramDocumentations != null) { return; } lock (LockObject) { if (_packageProgramDocumentations != null) { return; } var folder = Path.GetDirectoryName(new Uri(typeof(OracleHelpProvider).Assembly.CodeBase).LocalPath); using (var reader = XmlReader.Create(Path.Combine(folder, "OracleDocumentation.xml"))) { var documentation = (Documentation) new XmlSerializer(typeof(Documentation)).Deserialize(reader); _sqlFunctionDocumentation = documentation.Functions.ToLookup(f => f.Name.ToQuotedIdentifier()); _statementDocumentation = documentation.Statements.ToLookup(s => s.Name); var dataDictionaryObjects = documentation.DataDictionary.ToDictionary(o => OracleObjectIdentifier.Create(OracleObjectIdentifier.SchemaSys, o.Name)); _dataDictionaryObjects = dataDictionaryObjects.AsReadOnly(); var packageProgramDocumentations = new Dictionary <OracleProgramIdentifier, DocumentationPackageSubProgram>(); foreach (var packageDocumentation in documentation.Packages) { var packageIdentifier = OracleObjectIdentifier.Create(OracleObjectIdentifier.SchemaSys, packageDocumentation.Name); var dataDictionaryObjectDocumentation = new DocumentationDataDictionaryObject { Name = packageDocumentation.Name, Value = packageDocumentation.Description, Url = packageDocumentation.Url }; dataDictionaryObjects.Add(packageIdentifier, dataDictionaryObjectDocumentation); if (packageDocumentation.SubPrograms == null) { continue; } foreach (var subProgramDocumentation in packageDocumentation.SubPrograms) { subProgramDocumentation.PackageDocumentation = packageDocumentation; packageProgramDocumentations[OracleProgramIdentifier.CreateFromValues(OracleObjectIdentifier.SchemaSys, packageDocumentation.Name, subProgramDocumentation.Name)] = subProgramDocumentation; } } _packageProgramDocumentations = packageProgramDocumentations.AsReadOnly(); } } }
static HasCustomAttribute() { var d = new Dictionary <MetadataTable, uint>(); for (uint i = 0; i < s_tables.Length; ++i) { d.Add(s_tables[i], i); } s_inverseTables = d.AsReadOnly(); }
public void ShouldReturnAReadOnlyWrapperAroundDictionary() { // Given var dictionary = new Dictionary<string, object> { { "key", "value" } }; // When var readOnly = dictionary.AsReadOnly(); // Then Assert.True(dictionary.SequenceEqual(readOnly)); }
public void AsReadOnlyDictionaryTest() { IDictionary <string, string> dictionary = new Dictionary <string, string>() { { "A", "a" }, { "B", "b" }, { "C", "c" } }; Assert.IsFalse(dictionary.IsReadOnly); IDictionary <string, string> actual = dictionary.AsReadOnly(); Assert.IsTrue(actual.IsReadOnly); }
public void AsReadOnly_TurnsIDictionaryIntoReadOnlyDictionary() { IDictionary <string, string> dictionary = new Dictionary <string, string> { ["key1"] = "value1", ["key2"] = "value2" }; ReadOnlyDictionary <string, string> readOnlyDictionary = dictionary.AsReadOnly(); Assert.NotNull(readOnlyDictionary); Assert.Equal(dictionary["key1"], readOnlyDictionary["key1"]); Assert.Equal(dictionary["key2"], readOnlyDictionary["key2"]); Assert.Equal(dictionary.Count, readOnlyDictionary.Count); }
//public IReadOnlyDictionary<string, string> Dictionary { get; } = new ReadOnlyDictionary<string, string>(new Dictionary<string, string> //{ // { "1", "111" }, // { "2", "222" }, // { "3", "333" }, //}); //var dictionary = (Dictionary<string, string>)Dictionary; // possible //dictionary.Add("4", "444"); // possible //var sda = (Dictionary<string, AshxExtension>)RouteDefaults; //sda.TryAdd("s", null); /// <summary> /// 启动Ashx核心对象 /// </summary> /// <param name="Services"></param> public AshxBuilder(IServiceCollection Services) { this.Services = Services; AshxRoute = new AshxRouteHandler(this);//ReadOnlyDictionary AshxEndpoint = new AshxEndpointDataSource(this); Dictionary <string, AshxExtension> keys = GetAssembly(); RouteDefaults = keys.AsReadOnly(); //new ReadOnlyDictionary<string, AshxExtension>(new Dictionary<string, AshxExtension>(StringComparer.OrdinalIgnoreCase)); // new RouteValueDictionary(); }
public void AsReadOnlyTest() { var(str1, obj1) = ("obj1", new object()); var(str2, obj2) = ("obj2", new object()); var dict = new Dictionary <string, object>() { { str1, obj1 }, { str2, obj2 } }; var readOnlyDict = dict.AsReadOnly(); Assert.IsAssignableFrom <IReadOnlyDictionary <string, object> >(readOnlyDict); }
/// <summary> /// Reads the attributes. /// </summary> internal static IDictionary <string, object> ReadAttributes(IBinaryRawReader reader) { Debug.Assert(reader != null); var count = reader.ReadInt(); var res = new Dictionary <string, object>(count); for (var i = 0; i < count; i++) { res[reader.ReadString()] = reader.ReadObject <object>(); } return(res.AsReadOnly()); }
private async Task <IReadOnlyDictionary <StatementBase, IValidationModel> > BuildValidationModelsAsync(StatementCollection statements, string statementText, CancellationToken cancellationToken) { var dictionary = new Dictionary <StatementBase, IValidationModel>(); foreach (var statement in statements) { var semanticModel = await _validator.BuildSemanticModelAsync(statementText, statement, _databaseModel, cancellationToken); var validationModel = _validator.BuildValidationModel(semanticModel); dictionary.Add(statement, validationModel); } return(dictionary.AsReadOnly()); }
public SheeterContext( string sheetName, IEnumerable <TemplateContext> templateContexts, IReadOnlyDictionary <int, double> columnWidths ) { SheetName = sheetName; InitializeCellsAndRowHeights(); ColumnWidths = columnWidths.AsReadOnly(); void InitializeCellsAndRowHeights() { List <Cell> cells = new List <Cell>(); Dictionary <int, double> rowHeights = new Dictionary <int, double>(); int rowIndex = 0; foreach (TemplateContext context in templateContexts) { foreach (KeyValuePair <int, double> pair in context.RowHeights) { rowHeights.Add(rowIndex + pair.Key, pair.Value); } foreach (Cell cell in context.Cells) { Cell fixedCell = new Cell() { Value = cell.Value, Point = new System.Drawing.Point() { X = cell.Point.X, Y = cell.Point.Y + rowIndex }, Size = cell.Size, CellStyle = cell.CellStyle }; Debug.Assert(fixedCell.Point.Y == cell.Point.Y + rowIndex); cells.Add(fixedCell); } rowIndex += context.RowSpan; } Cells = cells.AsReadOnly(); RowHeights = rowHeights.AsReadOnly(); } }
public static IReadOnlyDictionary <string, MusicInfo> BuildMusicDictionary() { var result = new Dictionary <string, MusicInfo>(); foreach (var(name, path) in Music) { var extension = Path.GetExtension(path).Substring(1); var key = path.Substring(0, path.Length - extension.Length - 1); result.Add(key, new MusicInfo(key, new MiniYaml(name, new List <MiniYamlNode> { new MiniYamlNode("Extension", extension) }))); } return(result.AsReadOnly()); }
static PortalHelpers() { var d = new Dictionary <ReviewScopeEnum, string>(); foreach (var row in CSV.ParseText(Properties.Settings.Default.ReviewScopeWorkflowMapCsv)) { if (row.Length != 2) { continue; } var scope = Parse.ParseEnum <ReviewScopeEnum>(row[0]); d[scope] = StringHelpers.TrimOrNull(row[1]); } WorkflowDefinitionNameByReviewScope = d.AsReadOnly(); }
public static void AsReadOnly() { //dictionary.AsReadOnly turns dictionary to readonly dictionary //create dict var dict = new Dictionary <string, int> { { "a", 1 }, }; var readonlyDict = dict.AsReadOnly(); //error is expected Console.WriteLine("Change in readonlyDict, error is expected"); ((IDictionary <string, int>)readonlyDict).Add("b", 2); }
public void Test_unmodifiable_toString_methods() { // Regression for HARMONY-552 var al = new List <object>(); al.Add("a"); al.Add("b"); var uc = al.AsReadOnly(); assertEquals("[a, b]", uc.ToString()); var m = new Dictionary <string, string> { ["one"] = "1", ["two"] = "2" }; var um = m.AsReadOnly(); assertEquals("{one=1, two=2}", um.ToString()); }
public ColormapsType() { string[] names = { "lines", "pink", "copper", "bone", "gray", "winter", "autumn", "summer", "spring", "cool", "hot", "hsv", "jet", "parula" }; Names = names.AsReadOnly(); var assetHolder = UnityEngine.Resources.Load <GameObject>("Asset Holder").GetComponent <AssetHolder>(); Dictionary <ColormapId, Texture2D> textures = new Dictionary <ColormapId, Texture2D>() { [ColormapId.autumn] = assetHolder.Autumn, [ColormapId.bone] = assetHolder.Bone, [ColormapId.cool] = assetHolder.Cool, [ColormapId.copper] = assetHolder.Copper, [ColormapId.gray] = assetHolder.Gray, [ColormapId.hot] = assetHolder.Hot, [ColormapId.hsv] = assetHolder.Hsv, [ColormapId.jet] = assetHolder.Jet, [ColormapId.lines] = assetHolder.Lines, [ColormapId.parula] = assetHolder.Parula, [ColormapId.pink] = assetHolder.Pink, [ColormapId.spring] = assetHolder.Spring, [ColormapId.summer] = assetHolder.Summer, [ColormapId.winter] = assetHolder.Winter, }; Textures = textures.AsReadOnly(); }
public void IDictionaryAsReadOnlyWriteTest() { var dict = new Dictionary <int, string>(); foreach (int i in Enumerable.Range(0, 10)) { dict.Add(i, "" + i); } var readOnly = dict.AsReadOnly(); Assert.Throws(typeof(NotSupportedException), () => readOnly[0] = "fish"); Assert.Throws(typeof(NotSupportedException), () => readOnly[0] = "0"); Assert.Throws(typeof(NotSupportedException), () => readOnly[1] = "1"); Assert.Throws(typeof(NotSupportedException), () => readOnly[500] = "NintySeven"); Assert.Throws(typeof(NotSupportedException), () => readOnly.Clear()); Assert.Throws(typeof(NotSupportedException), () => readOnly.Keys.Clear()); Assert.Throws(typeof(NotSupportedException), () => readOnly.Values.Clear()); Assert.Throws(typeof(NotSupportedException), () => readOnly.Add(15, "House")); Assert.Throws(typeof(NotSupportedException), () => readOnly.Remove(5)); }
public void AsReadOnly_Wraps_Source_In_ReadOnlyDictionary() { // ARRABGE var source = new Dictionary <string, int> { ["Foo"] = 10, ["Bar"] = 45 }; // ACT var result = source.AsReadOnly(); // ASSERT Assert.IsNotNull(result); Assert.AreEqual(2, result.Count); Assert.IsTrue(result.ContainsKey("Foo")); Assert.IsTrue(result.ContainsKey("Bar")); Assert.AreEqual(10, result["Foo"]); Assert.AreEqual(45, result["Bar"]); }
public void IDictionaryAsReadOnlyReadTest() { var dict = new Dictionary <int, string>(); foreach (int i in Enumerable.Range(0, 10)) { dict.Add(i, "" + i); } var readOnly = dict.AsReadOnly(); foreach (int i in Enumerable.Range(0, 10)) { Assert.AreEqual(i.ToString(), readOnly[i]); } foreach (int i in dict.Keys) { Assert.AreEqual(dict[i], readOnly[i]); } }
private static IDictionary <string, MethodInfo> LoadDefaultFunctions() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006) { IDictionary <string, MethodInfo> map = new Dictionary <string, MethodInfo>(); try { foreach (var property in GetDefaultSettings()) { string[] vals = property.Value.Split(',').TrimEnd(); if (vals.Length != 3) { throw new Exception("Error reading Javascript functions from settings"); } string typeName = vals[0]; Type clazz; if (vals[0].Contains("Lucene.Net")) { clazz = GetType(vals[0] + ", Lucene.Net"); } else { clazz = GetType(typeName); } string methodName = vals[1].Trim(); int arity = int.Parse(vals[2], CultureInfo.InvariantCulture); Type[] args = new Type[arity]; Arrays.Fill(args, typeof(double)); MethodInfo method = clazz.GetMethod(methodName, args); CheckFunction(method); map[property.Key] = method; } } catch (Exception e) { throw new Exception("Cannot resolve function", e); } return(map.AsReadOnly()); }
public CursorProvider(ModData modData) { var sequenceFiles = modData.Manifest.Cursors; var partial = sequenceFiles .Select(s => MiniYaml.FromFile(s)) .Aggregate(MiniYaml.MergePartial); var sequences = new MiniYaml(null, MiniYaml.ApplyRemovals(partial)); var shadowIndex = new int[] { }; var nodesDict = sequences.ToDictionary(); if (nodesDict.ContainsKey("ShadowIndex")) { Array.Resize(ref shadowIndex, shadowIndex.Length + 1); Exts.TryParseIntegerInvariant(nodesDict["ShadowIndex"].Value, out shadowIndex[shadowIndex.Length - 1]); } var palettes = new Dictionary <string, ImmutablePalette>(); foreach (var p in nodesDict["Palettes"].Nodes) { palettes.Add(p.Key, new ImmutablePalette(modData.ModFiles.Open(p.Value.Value), shadowIndex)); } Palettes = palettes.AsReadOnly(); var frameCache = new FrameCache(modData.SpriteLoaders); var cursors = new Dictionary <string, CursorSequence>(); foreach (var s in nodesDict["Cursors"].Nodes) { foreach (var sequence in s.Value.Nodes) { cursors.Add(sequence.Key, new CursorSequence(frameCache, sequence.Key, s.Key, s.Value.Value, sequence.Value)); } } Cursors = cursors.AsReadOnly(); }
protected FuzzyLambda(IEnumerable<String> args) // bug: jeez... that's wtf // : base(ReflectionHelper.ForgeFuncType(args.Count())) : base(ReflectionHelper.ForgeFuncType(args.Count()).ForgeTypedLambda()) { var fuzzyArgs = new Dictionary<String, FuzzyType>(); var position = 0; foreach (var arg in args) { var realLambdaType = GenericArgs[0]; fuzzyArgs[arg] = realLambdaType.GenericArgs[position++]; } Args = fuzzyArgs.AsReadOnly(); // Register typepoints for debug -> 0 downtime in release, but immensely useful in debug mode // bug: jeez... that's wtf // ReturnValue.RegDebuggableParent(this).SetDesc("ret"); // Args.ForEach((arg, i) => arg.Value.RegDebuggableParent(this).SetDesc("arg"+i)); }
public void Test_ReadOnly() { var pair = new KeyValuePair <int, string>(10, "c"); var dictionary = new Dictionary <int, string>() { { 1, "a" }, { 2, "b" }, { 10, "c" }, { 7, "d" }, { 12, "e" } }; var dictionary2 = dictionary.AsReadOnly(); Assert.Equal(5, dictionary2.Count); var check = Assert.Throws <NotSupportedException>(() => dictionary2.Remove(pair)); Assert.Equal("Dictionary is read only!", check.Message); }
/// <summary> /// Initializes a new instance of the <see cref="ServiceDescriptor" /> class. /// </summary> /// <param name="name">Name.</param> /// <param name="reader">Reader.</param> /// <param name="services">Services.</param> public ServiceDescriptor(string name, BinaryReader reader, IServices services) { Debug.Assert(reader != null); Debug.Assert(services != null); Debug.Assert(!string.IsNullOrEmpty(name)); _services = services; Name = name; CacheName = reader.ReadString(); MaxPerNodeCount = reader.ReadInt(); TotalCount = reader.ReadInt(); OriginNodeId = reader.ReadGuid() ?? Guid.Empty; AffinityKey = reader.ReadObject<object>(); var mapSize = reader.ReadInt(); var snap = new Dictionary<Guid, int>(mapSize); for (var i = 0; i < mapSize; i++) snap[reader.ReadGuid() ?? Guid.Empty] = reader.ReadInt(); TopologySnapshot = snap.AsReadOnly(); }
private void DebuggerSessionDetachedHandler(object sender, EventArgs args) { var statementResult = _debuggerSession.ExecutionResult.StatementResults[0]; var resultInfoColumnHeaders = new Dictionary<ResultInfo, IReadOnlyList<ColumnHeader>>(); resultInfoColumnHeaders.AddRange(AcquireImplicitRefCursors(_debuggerSession.DebuggedCommand)); resultInfoColumnHeaders.AddRange(UpdateBindVariables(statementResult.StatementModel, _debuggerSession.DebuggedCommand)); _resultInfoColumnHeaders.AddRange(resultInfoColumnHeaders); statementResult.ResultInfoColumnHeaders = resultInfoColumnHeaders.AsReadOnly(); _debuggerSession.Detached -= DebuggerSessionDetachedHandler; _debuggerSession.Dispose(); _debuggerSession = null; }
private async Task<StatementExecutionBatchResult> ExecuteUserStatementAsync(StatementBatchExecutionModel batchExecutionModel, bool isReferenceConstraintNavigation, CancellationToken cancellationToken) { if (batchExecutionModel.Statements == null || batchExecutionModel.Statements.Count == 0) { throw new ArgumentException("An execution batch must contain at least one statement. ", nameof(batchExecutionModel)); } _isExecuting = true; _userCommandHasCompilationErrors = false; var batchResult = new StatementExecutionBatchResult { ExecutionModel = batchExecutionModel }; var statementResults = new List<StatementExecutionResult>(); StatementExecutionResult currentStatementResult = null; try { SetOracleGlobalization(); await EnsureUserConnectionOpen(cancellationToken); await EnsureDatabaseOutput(cancellationToken); if (batchExecutionModel.GatherExecutionStatistics) { _executionStatisticsDataProvider = new SessionExecutionStatisticsDataProvider(_databaseModel.StatisticsKeys, _userSessionIdentifier.Value.SessionId); await _databaseModel.UpdateModelAsync(true, cancellationToken, _executionStatisticsDataProvider.SessionBeginExecutionStatisticsDataProvider); } _userConnection.ActionName = "User command"; foreach (var executionModel in batchExecutionModel.Statements) { currentStatementResult = new StatementExecutionResult { StatementModel = executionModel }; statementResults.Add(currentStatementResult); if (_userTransaction == null) { var isolationLevel = executionModel.Statement?.RootNode[NonTerminals.Statement, NonTerminals.SetTransactionStatement, NonTerminals.TransactionModeOrIsolationLevelOrRollbackSegment, NonTerminals.SerializableOrReadCommitted, Terminals.Serializable] != null ? IsolationLevel.Serializable : IsolationLevel.ReadCommitted; _userTransaction = _userConnection.BeginTransaction(isolationLevel); } var userCommand = InitializeUserCommand(); userCommand.CommandText = executionModel.StatementText.Replace("\r\n", "\n"); foreach (var variable in executionModel.BindVariables) { var value = await GetBindVariableValue(variable, cancellationToken); userCommand.AddSimpleParameter(variable.Name, value, variable.DataType.Name); } var resultInfoColumnHeaders = new Dictionary<ResultInfo, IReadOnlyList<ColumnHeader>>(); var statement = (OracleStatement)executionModel.Statement; var isPlSql = statement?.IsPlSql ?? false; if (isPlSql && batchExecutionModel.EnableDebug && executionModel.IsPartialStatement) { throw new InvalidOperationException("Debugging is not supported for PL/SQL fragment. "); } if (isPlSql) { currentStatementResult.ExecutedAt = DateTime.Now; if (batchExecutionModel.EnableDebug) { // TODO: Add COMPILE DEBUG _debuggerSession = new OracleDebuggerSession(this, (OracleCommand)userCommand.Clone(), batchResult); _debuggerSession.Detached += DebuggerSessionDetachedHandler; } else { currentStatementResult.AffectedRowCount = await userCommand.ExecuteNonQueryAsynchronous(cancellationToken); currentStatementResult.Duration = DateTime.Now - currentStatementResult.ExecutedAt; resultInfoColumnHeaders.AddRange(AcquireImplicitRefCursors(userCommand)); } } else { currentStatementResult.ExecutedAt = DateTime.Now; var dataReader = await userCommand.ExecuteReaderAsynchronous(CommandBehavior.Default, cancellationToken); currentStatementResult.Duration = DateTime.Now - currentStatementResult.ExecutedAt; currentStatementResult.AffectedRowCount = dataReader.RecordsAffected; var resultInfo = isReferenceConstraintNavigation ? new ResultInfo($"ReferenceConstrantResult{dataReader.GetHashCode()}", null, ResultIdentifierType.SystemGenerated) : new ResultInfo($"MainResult{dataReader.GetHashCode()}", $"Result set {_resultInfoColumnHeaders.Count + 1}", ResultIdentifierType.UserDefined); var columnHeaders = GetColumnHeadersFromReader(dataReader); if (columnHeaders.Count > 0) { _commandReaders.Add(resultInfo, new CommandReader { Reader = dataReader, Command = userCommand } ); resultInfoColumnHeaders.Add(resultInfo, columnHeaders); } } resultInfoColumnHeaders.AddRange(UpdateBindVariables(currentStatementResult.StatementModel, userCommand)); currentStatementResult.ResultInfoColumnHeaders = resultInfoColumnHeaders.AsReadOnly(); _resultInfoColumnHeaders.AddRange(resultInfoColumnHeaders); currentStatementResult.CompilationErrors = _userCommandHasCompilationErrors ? await RetrieveCompilationErrors(executionModel.ValidationModel.Statement, cancellationToken) : CompilationError.EmptyArray; currentStatementResult.SuccessfulExecutionMessage = statement == null ? OracleStatement.DefaultMessageCommandExecutedSuccessfully : statement.BuildExecutionFeedbackMessage(currentStatementResult.AffectedRowCount, _userCommandHasCompilationErrors); } } catch (OracleException exception) { if (currentStatementResult == null) { statementResults.Add( new StatementExecutionResult { StatementModel = batchExecutionModel.Statements[0], Exception = exception }); } else { currentStatementResult.Exception = exception; if (currentStatementResult.ExecutedAt != null && currentStatementResult.Duration == null) { currentStatementResult.Duration = DateTime.Now - currentStatementResult.ExecutedAt; } } var executionException = new StatementExecutionException(batchResult, exception); var isConnectionTerminated = TryHandleConnectionTerminatedError(exception); if (isConnectionTerminated) { throw executionException; } if (exception.Number == (int)OracleErrorCode.UserInvokedCancellation) { return batchResult; } if (currentStatementResult != null) { currentStatementResult.ErrorPosition = await GetSyntaxErrorIndex(currentStatementResult.StatementModel.StatementText, cancellationToken); } throw executionException; } finally { batchResult.StatementResults = statementResults.AsReadOnly(); try { if (_userConnection.State == ConnectionState.Open && !batchExecutionModel.EnableDebug && !cancellationToken.IsCancellationRequested) { await FinalizeBatchExecution(batchResult, cancellationToken); } } finally { _isExecuting = false; } } return batchResult; }
public void IDictionaryAsReadOnlyWriteTest() { var dict = new Dictionary<int, string>(); foreach (int i in Enumerable.Range(0, 10)) { dict.Add(i, "" + i); } var readOnly = dict.AsReadOnly(); Assert.Throws(typeof(NotSupportedException), () => readOnly[0] = "fish"); Assert.Throws(typeof(NotSupportedException), () => readOnly[0] = "0"); Assert.Throws(typeof(NotSupportedException), () => readOnly[1] = "1"); Assert.Throws(typeof(NotSupportedException), () => readOnly[500] = "NintySeven"); Assert.Throws(typeof(NotSupportedException), () => readOnly.Clear()); Assert.Throws(typeof(NotSupportedException), () => readOnly.Keys.Clear()); Assert.Throws(typeof(NotSupportedException), () => readOnly.Values.Clear()); Assert.Throws(typeof(NotSupportedException), () => readOnly.Add(15, "House")); Assert.Throws(typeof(NotSupportedException), () => readOnly.Remove(5)); }
private IDictionary<string, object> TranslateImportMetadata(ContractBasedImportDefinition originalImport) { int[] importParametersOrder = originalImport.Metadata.GetValue<int[]>(CompositionConstants.GenericImportParametersOrderMetadataName); if (importParametersOrder != null) { Dictionary<string, object> metadata = new Dictionary<string, object>(originalImport.Metadata, StringComparers.MetadataKeyNames); // Get the newly re-qualified name of the generic contract and the subset of applicable types from the specialization metadata[CompositionConstants.GenericContractMetadataName] = GenericServices.GetGenericName(originalImport.ContractName, importParametersOrder, this._specialization.Length); metadata[CompositionConstants.GenericParametersMetadataName] = GenericServices.Reorder(this._specialization, importParametersOrder); metadata.Remove(CompositionConstants.GenericImportParametersOrderMetadataName); return metadata.AsReadOnly(); } else { return originalImport.Metadata; } }
public ImapNamespaceDesc Clone() { var cloned = (ImapNamespaceDesc)MemberwiseClone(); var extensions = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); foreach (var pair in Extensions) { extensions.Add(pair.Key, (string[])pair.Value.Clone()); } cloned.Extensions = extensions.AsReadOnly(); return cloned; }
public void IDictionaryAsReadOnlyReadTest() { var dict = new Dictionary<int, string>(); foreach (int i in Enumerable.Range(0, 10)) { dict.Add(i, "" + i); } var readOnly = dict.AsReadOnly(); foreach (int i in Enumerable.Range(0, 10)) { Assert.AreEqual(i.ToString(), readOnly[i]); } foreach (int i in dict.Keys) { Assert.AreEqual(dict[i], readOnly[i]); } }
private static void EnsureDocumentationDictionaries() { if (_packageProgramDocumentations != null) { return; } lock (LockObject) { if (_packageProgramDocumentations != null) { return; } var folder = new Uri(Path.GetDirectoryName(typeof (OracleHelpProvider).Assembly.CodeBase)).LocalPath; using (var reader = XmlReader.Create(Path.Combine(folder, "OracleDocumentation.xml"))) { var documentation = (Documentation)new XmlSerializer(typeof(Documentation)).Deserialize(reader); _sqlFunctionDocumentation = documentation.Functions.ToLookup(f => f.Name.ToQuotedIdentifier()); _statementDocumentation = documentation.Statements.ToLookup(s => s.Name); var dataDictionaryObjects = documentation.DataDictionary.ToDictionary(o => OracleObjectIdentifier.Create(OracleObjectIdentifier.SchemaSys, o.Name)); _dataDictionaryObjects = dataDictionaryObjects.AsReadOnly(); var packageProgramDocumentations = new Dictionary<OracleProgramIdentifier, DocumentationPackageSubProgram>(); foreach (var packageDocumentation in documentation.Packages) { var packageIdentifier = OracleObjectIdentifier.Create(OracleObjectIdentifier.SchemaSys, packageDocumentation.Name); var dataDictionaryObjectDocumentation = new DocumentationDataDictionaryObject { Name = packageDocumentation.Name, Value = packageDocumentation.Description, Url = packageDocumentation.Url }; dataDictionaryObjects.Add(packageIdentifier, dataDictionaryObjectDocumentation); if (packageDocumentation.SubPrograms == null) { continue; } foreach (var subProgramDocumentation in packageDocumentation.SubPrograms) { subProgramDocumentation.PackageDocumentation = packageDocumentation; packageProgramDocumentations[OracleProgramIdentifier.CreateFromValues(OracleObjectIdentifier.SchemaSys, packageDocumentation.Name, subProgramDocumentation.Name)] = subProgramDocumentation; } } _packageProgramDocumentations = packageProgramDocumentations.AsReadOnly(); } } }