Example #1
0
        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();
        }
        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();
        }
Example #3
0
 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));
            }
Example #5
0
        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));
        }
        /// <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 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;
            }
        }
Example #8
0
        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;
        }
Example #9
0
		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();
				}
			}
		}
Example #10
0
		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;
		}
Example #11
0
		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;
		}
Example #12
0
        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));
        }
Example #13
0
        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]);
            }
        }