/// <summary> /// Asynchronously creates a message for writing an async response. /// </summary> /// <returns>The message that can be used to write the async response.</returns> public Task <ODataAsynchronousResponseMessage> CreateResponseMessageAsync() { this.VerifyCanCreateResponseMessage(false); return(TaskUtils.GetTaskForSynchronousOperation(() => this.CreateResponseMessageImplementation())); }
private async void ReadRows() { if (_executeQuery) { return; } if (_gdbPath.IsEmpty()) { return; } if (SelectedTableName.IsEmpty()) { return; } _executeQuery = true; _columns.Clear(); _timer.Start(); OnPropertyChanged("IsExecutingQuery"); string tableName = SelectedTableName.Split(new char[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)[1].Trim(); var data = new ObservableCollection <DynamicDataRow>(); try { //Note, we have to return something await TaskUtils.StartSTATask <int>(() => { using (Geodatabase gdb = new Geodatabase(_gdbPath)) { var table = gdb.OpenDataset <Table>(tableName); RowCursor cursor = table.Search(); IReadOnlyList <Field> flds = cursor.GetFields(); foreach (var fld in flds) { _columns.Add(new ColumnData() { AliasName = fld.AliasName ?? fld.Name, Name = fld.Name, FieldType = fld.FieldType }); } while (cursor.MoveNext()) { var row = new DynamicDataRow(); for (int v = 0; v < flds.Count; v++) { row[GetName(flds[v])] = GetValue(cursor.Current, v); } data.Add(row); } } return(0); }); } finally { ExtendListView.Columns = _columns; _timer.Stop(); lock (_theLock) { _rows.Clear(); _rows = null; _rows = data; } if (_rows.Count > 0) { TableHasNoRows = ""; } else { TableHasNoRows = "No rows returned"; } _executeQuery = false; OnPropertyChanged("Rows"); OnPropertyChanged("IsExecutingQuery"); } }
public async Task WriteResponseMessage_APIsShouldYieldSameResult() { var nestedWriterSettings = new ODataMessageWriterSettings { Version = ODataVersion.V4, EnableMessageStreamDisposal = false }; nestedWriterSettings.SetServiceDocumentUri(new Uri(ServiceUri)); var customerResponse = new ODataResource { TypeName = "NS.Customer", Properties = new List <ODataProperty> { new ODataProperty { Name = "Id", Value = 1, SerializationInfo = new ODataPropertySerializationInfo { PropertyKind = ODataPropertyKind.Key } }, new ODataProperty { Name = "Name", Value = "Customer 1" } } }; IODataResponseMessage asyncResponseMessage = new InMemoryMessage { StatusCode = 200, Stream = this.asyncStream }; using (var messageWriter = new ODataMessageWriter(asyncResponseMessage, writerSettings)) { var asynchronousWriter = await messageWriter.CreateODataAsynchronousWriterAsync(); var responseMessage = await asynchronousWriter.CreateResponseMessageAsync(); responseMessage.StatusCode = 200; using (var nestedMessageWriter = new ODataMessageWriter(responseMessage, nestedWriterSettings, this.model)) { var writer = await nestedMessageWriter.CreateODataResourceWriterAsync(this.customerEntitySet, this.customerEntityType); await writer.WriteStartAsync(customerResponse); await writer.WriteEndAsync(); await writer.FlushAsync(); } await asynchronousWriter.FlushAsync(); } this.asyncStream.Position = 0; var asyncResult = await new StreamReader(this.asyncStream).ReadToEndAsync(); var syncResult = await TaskUtils.GetTaskForSynchronousOperation(() => { IODataResponseMessage syncResponseMessage = new InMemoryMessage { StatusCode = 200, Stream = this.syncStream }; using (var messageWriter = new ODataMessageWriter(syncResponseMessage, writerSettings)) { var asynchronousWriter = messageWriter.CreateODataAsynchronousWriter(); var responseMessage = asynchronousWriter.CreateResponseMessage(); responseMessage.StatusCode = 200; using (var nestedMessageWriter = new ODataMessageWriter(responseMessage, nestedWriterSettings, this.model)) { var writer = nestedMessageWriter.CreateODataResourceWriter(this.customerEntitySet, this.customerEntityType); writer.WriteStart(customerResponse); writer.WriteEnd(); writer.Flush(); } asynchronousWriter.Flush(); } this.syncStream.Position = 0; return(new StreamReader(this.syncStream).ReadToEnd()); }); var expected = @"HTTP/1.1 200 OK OData-Version: 4.0 Content-Type: application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false;charset=utf-8 {""@odata.context"":""http://tempuri.org/$metadata#Customers/$entity"",""Id"":1,""Name"":""Customer 1""}"; Assert.Equal(expected, asyncResult); Assert.Equal(expected, syncResult); }
/// <summary> /// Asynchronously get the stream backing this message. /// </summary> /// <param name="streamFuncAsync">A function that returns a task for the stream backing the message.</param> /// <param name="isRequest">true if the message is a request message; false for a response message.</param> /// <returns>A task that when completed returns the stream backing the message.</returns> protected internal Task <Stream> GetStreamAsync(Func <Task <Stream> > streamFuncAsync, bool isRequest) { // Check whether we have an existing buffering read stream when reading if (!this.writing) { Stream existingBufferingReadStream = this.TryGetBufferingReadStream(); Debug.Assert(!this.writing || existingBufferingReadStream == null, "The buffering read stream should only be used when reading."); if (existingBufferingReadStream != null) { Debug.Assert(this.useBufferingReadStream.HasValue, "UseBufferingReadStream must have been set."); return(TaskUtils.GetCompletedTask(existingBufferingReadStream)); } } Task <Stream> task = streamFuncAsync(); ValidateMessageStreamTask(task, isRequest); // Wrap it in a non-disposing stream if requested task = task.FollowOnSuccessWith( streamTask => { Stream messageStream = streamTask.Result; ValidateMessageStream(messageStream, isRequest); // When reading, wrap the stream in a byte counting stream if a max message size was specified. // When requested, wrap the stream in a non-disposing stream. bool needByteCountingStream = !this.writing && this.maxMessageSize > 0; if (!this.enableMessageStreamDisposal && needByteCountingStream) { messageStream = MessageStreamWrapper.CreateNonDisposingStreamWithMaxSize(messageStream, this.maxMessageSize); } else if (!this.enableMessageStreamDisposal) { messageStream = MessageStreamWrapper.CreateNonDisposingStream(messageStream); } else if (needByteCountingStream) { messageStream = MessageStreamWrapper.CreateStreamWithMaxSize(messageStream, this.maxMessageSize); } return(messageStream); }); // When we are reading, also buffer the input stream if (!this.writing) { task = task .FollowOnSuccessWithTask( streamTask => { return(BufferedReadStream.BufferStreamAsync(streamTask.Result)); }) .FollowOnSuccessWith( streamTask => { BufferedReadStream bufferedReadStream = streamTask.Result; return((Stream)bufferedReadStream); }); // If requested also create a buffering stream for payload kind detection if (this.useBufferingReadStream == true) { task = task.FollowOnSuccessWith( streamTask => { Stream messageStream = streamTask.Result; this.bufferingReadStream = new BufferingReadStream(messageStream); messageStream = this.bufferingReadStream; return(messageStream); }); } } return(task); }
public ScenarioStatisticsRegistration GetStatisticsRegistration(string[] scenariosIds) { var scenarios = ScenariosRepository.Scenarios.Where(x => scenariosIds.Contains(x.Id)).ToArray(); return(TaskUtils.Wait(StatisticsManager.GetRegistrationInfo(scenarios))); }
public override Task <Schema> GetSchemaAsync(ICRUDQueryExecutionContext context, Query query) { return(TaskUtils.AsCompletedTask(() => this.GetSchema(context, query))); }
public override Task <Cursor> OpenCursorAsync(ICRUDQueryExecutionContext context, Query query) { return(TaskUtils.AsCompletedTask(() => this.OpenCursor(context, query))); }
/// <summary> /// Asynchronously creates an <see cref="ODataCollectionWriter" /> to write a collection of primitive or complex values (as result of a service operation invocation). /// </summary> /// <param name="itemTypeReference">The item type of the collection being written or null if no metadata is available.</param> /// <returns>A running task for the created collection writer.</returns> /// <remarks>The write must flush the output when it's finished (inside the last Write call).</remarks> internal override Task <ODataCollectionWriter> CreateODataCollectionWriterAsync(IEdmTypeReference itemTypeReference) { this.AssertAsynchronous(); return(TaskUtils.GetTaskForSynchronousOperation(() => this.CreateODataCollectionWriterImplementation(itemTypeReference))); }
/// <inheritdoc/> public override Task WriteLineAsync(char[] buffer, int index, int count) { return(TaskUtils.GetTaskForSynchronousOperation(() => this.WriteLine(buffer, index, count))); }
/// <summary> /// Asynchronously creates an <see cref="ODataWriter" /> to write a feed. /// </summary> /// <param name="entitySet">The entity set we are going to write entities for.</param> /// <param name="entityType">The entity type for the entries in the feed to be written (or null if the entity set base type should be used).</param> /// <returns>A running task for the created writer.</returns> /// <remarks>The write must flush the output when it's finished (inside the last Write call).</remarks> internal override Task <ODataWriter> CreateODataFeedWriterAsync(IEdmEntitySetBase entitySet, IEdmEntityType entityType) { this.AssertAsynchronous(); return(TaskUtils.GetTaskForSynchronousOperation(() => this.CreateODataFeedWriterImplementation(entitySet, entityType))); }
/// <summary> /// Asynchronously creates an <see cref="ODataWriter" /> to write an entry. /// </summary> /// <param name="navigationSource">The navigation source we are going to write entities for.</param> /// <param name="entityType">The entity type for the entries in the feed to be written (or null if the entity set base type should be used).</param> /// <returns>A running task for the created writer.</returns> /// <remarks>The write must flush the output when it's finished (inside the last Write call).</remarks> internal override Task <ODataWriter> CreateODataEntryWriterAsync(IEdmNavigationSource navigationSource, IEdmEntityType entityType) { this.AssertAsynchronous(); return(TaskUtils.GetTaskForSynchronousOperation(() => this.CreateODataEntryWriterImplementation(navigationSource, entityType))); }
public Task RegisterTerrain(WeldingInputTerrain inputTerrain) { _terrains[inputTerrain.WeldingInputTerrainId] = new WeldingTerrainEntity() { Uvs = new TerrainWeldUvs(), WeldModificationCallback = inputTerrain.WeldModificationCallback }; var globalSubPosition = RectangleUtils.CalculateSubPosition(inputTerrain.DetailGlobalArea, inputTerrain.UvCoordsPositions2D); var weldPositions = new Dictionary <WeldSideType, WeldPosition>(); weldPositions[WeldSideType.Bottom] = new WeldPosition() { ConstantAxisPosition = Mathf.RoundToInt(globalSubPosition.Y), Orientation = WeldOrientation.Horizontal, Range = new IntVector2(Mathf.RoundToInt(globalSubPosition.X), Mathf.RoundToInt(globalSubPosition.MaxX)) }; weldPositions[WeldSideType.Top] = new WeldPosition() { ConstantAxisPosition = Mathf.RoundToInt(globalSubPosition.MaxY), Orientation = WeldOrientation.Horizontal, Range = new IntVector2(Mathf.RoundToInt(globalSubPosition.X), Mathf.RoundToInt(globalSubPosition.MaxX)) }; weldPositions[WeldSideType.Left] = new WeldPosition() { ConstantAxisPosition = Mathf.RoundToInt(globalSubPosition.X), Orientation = WeldOrientation.Vertical, Range = new IntVector2(Mathf.RoundToInt(globalSubPosition.Y), Mathf.RoundToInt(globalSubPosition.MaxY)) }; weldPositions[WeldSideType.Right] = new WeldPosition() { ConstantAxisPosition = Mathf.RoundToInt(globalSubPosition.MaxX), Orientation = WeldOrientation.Vertical, Range = new IntVector2(Mathf.RoundToInt(globalSubPosition.Y), Mathf.RoundToInt(globalSubPosition.MaxY)) }; var orders = new List <WeldRegenerationOrder>(); foreach (var weldPositionPair in weldPositions) { var weldPosition = weldPositionPair.Value; var orientation = weldPositionPair.Key.GetOrientation(); var weldsDict = _welds[orientation]; if (!weldsDict.ContainsKey(weldPosition.ConstantAxisPosition)) { weldsDict[weldPosition.ConstantAxisPosition] = new WeldLine(); } var line = weldsDict[weldPosition.ConstantAxisPosition]; orders.AddRange(line.RegisterWeld(weldPosition, weldPositionPair.Key, inputTerrain)); } //var weldsUvs = TaskUtils.WhenAll(orders.Select(c => _mapLevel1Manager.Process(c))).Result; var weldsUvs = orders.Select(c => _mapLevel1Manager.Process(c)).ToList(); foreach (var x in weldsUvs.SelectMany(c => c)) { var terrainId = x.Key; var weldUv = x.Value; var terrain = _terrains[terrainId]; terrain.Uvs.Merge(weldUv); terrain.WeldModificationCallback(terrain.Uvs); } return(TaskUtils.EmptyCompleted()); }
public async Task TesttArity1() { Tuple <long> results = await TaskUtils.All(get1()); Assert.Equal(1, results.Item1); }
public Task CreatedNewNodeAsync() { return(TaskUtils.EmptyCompleted()); }
/// <summary> /// Asynchronously read a top-level value. /// </summary> /// <param name="expectedPrimitiveTypeReference">The expected type reference for the value to be read; null if no expected type is available.</param> /// <returns>Task which when completed returns an <see cref="object"/> representing the read value.</returns> internal override Task <object> ReadValueAsync(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference) { // Note that the reading is actually synchronous since we buffer the entire input when getting the stream from the message. return(TaskUtils.GetTaskForSynchronousOperation(() => this.ReadValueImplementation(expectedPrimitiveTypeReference))); }
/// <inheritdoc/> public override Task WriteLineAsync(string value) { return(TaskUtils.GetTaskForSynchronousOperation(() => this.WriteLine(value))); }
/// <summary> /// Asynchronously create an <see cref="ODataAsynchronousReader"/>. /// </summary> /// <returns>Task which when completed returns the newly created <see cref="ODataAsynchronousReader"/>.</returns> internal override Task <ODataAsynchronousReader> CreateAsynchronousReaderAsync() { // Note that the reading is actually synchronous since we buffer the entire input when getting the stream from the message. return(TaskUtils.GetTaskForSynchronousOperation(() => this.CreateAsynchronousReaderImplementation())); }
/// <summary> /// Implementation of the reader logic when in state Value, Resource, Resource Set or Collection state. /// </summary> /// <returns>true if more items can be read from the reader; otherwise false.</returns> /// <remarks> /// Pre-Condition: JsonNodeType.Property or JsonNodeType.EndObject: assumes the last read puts the reader at the beginning of the next parameter or at the end of the payload. /// Post-Condition: When the new state is Value, the reader is positioned at the closing '}' or at the name of the next parameter. /// When the new state is Resource, the reader is positioned at the starting '{' of the resource payload. /// When the new state is Resource Set or Collection, the reader is positioned at the starting '[' of the resource set or collection payload. /// </remarks> protected override Task <bool> ReadNextParameterImplementationAsync() { return(TaskUtils.GetTaskForSynchronousOperation <bool>(this.ReadNextParameterImplementationSynchronously)); }
public override Task <RowsetBase> ExecuteAsync(ICRUDQueryExecutionContext context, Query query, bool oneRow = false) { return(TaskUtils.AsCompletedTask(() => this.Execute(context, query, oneRow))); }
/// <summary> /// Creates an <see cref="ODataReader"/> to read the resource set value of type <paramref name="expectedResourceType"/>. /// </summary> /// <param name="expectedResourceType">Expected resource set element type to read.</param> /// <returns>An <see cref="ODataReader"/> to read the resource set value of type <paramref name="expectedResourceType"/>.</returns> protected override Task <ODataReader> CreateResourceSetReaderAsync(IEdmStructuredType expectedResourceType) { return(TaskUtils.GetTaskForSynchronousOperation <ODataReader>(() => this.CreateResourceSetReaderSynchronously(expectedResourceType))); }
public override Task <int> ExecuteWithoutFetchAsync(ICRUDQueryExecutionContext context, Query query) { return(TaskUtils.AsCompletedTask(() => this.ExecuteWithoutFetch(context, query))); }
/// <summary> /// Creates an <see cref="ODataCollectionReader"/> to read the collection with type <paramref name="expectedItemTypeReference"/>. /// </summary> /// <param name="expectedItemTypeReference">Expected item type reference of the collection to read.</param> /// <returns>An <see cref="ODataCollectionReader"/> to read the collection with type <paramref name="expectedItemTypeReference"/>.</returns> /// <remarks> /// Pre-Condition: Any: the reader should be on the start array node of the collection value; if it is not we let the collection reader fail. /// Post-Condition: Any: the reader should be on the start array node of the collection value; if it is not we let the collection reader fail. /// NOTE: this method does not move the reader. /// </remarks> protected override Task <ODataCollectionReader> CreateCollectionReaderAsync(IEdmTypeReference expectedItemTypeReference) { return(TaskUtils.GetTaskForSynchronousOperation <ODataCollectionReader>(() => this.CreateCollectionReaderSynchronously(expectedItemTypeReference))); }
public ScenarioStatistic GetStatistics(DateTime since, DateTime to, StatisticsScenarioInfo info) { var user = GetCurrentUser(); return(TaskUtils.Wait(StatisticsManager.GetItems(info, since, to, new ScenarioActionSource(user, ScenarioStartupSource.Network, ScenarioAction.ViewValue)))); }
/// <summary> /// Asynchronously creates an <see cref="ODataBatchWriter" /> to write a batch of requests or responses. /// </summary> /// <param name="batchBoundary">The boundary string for the batch structure itself.</param> /// <returns>A running task for the created batch writer.</returns> /// <remarks>We don't plan to make this public!</remarks> /// <remarks>The write must flush the output when it's finished (inside the last Write call).</remarks> internal override Task <ODataBatchWriter> CreateODataBatchWriterAsync(string batchBoundary) { this.AssertAsynchronous(); return(TaskUtils.GetTaskForSynchronousOperation(() => this.CreateODataBatchWriterImplementation(batchBoundary))); }
private async void OpenGDB() { if (_executeQuery) { return; } if (_gdbPath.IsEmpty()) { return; } _executeQuery = true; _timer.Start(); OnPropertyChanged("IsExecutingQuery"); _tables.Clear(); if (_rows.Count > 0) { _rows.Clear(); _rows = new ObservableCollection <DynamicDataRow>(); ExtendListView.Columns = null; OnPropertyChanged("Rows"); } TableHasNoRows = ""; SelectedTableName = ""; try { await TaskUtils.StartSTATask <int>(() => { using (Geodatabase gdb = new Geodatabase(_gdbPath)) { IReadOnlyList <Definition> fcList = gdb.GetDefinitions <FeatureClassDefinition>(); IReadOnlyList <Definition> tables = gdb.GetDefinitions <TableDefinition>(); //////Uncomment for just Feature class in Feature Datasets ////IReadOnlyList<Definition> fdsList = gdb.GetDefinitions<FeatureDatasetDefinition>(); lock (_theLock) { //Feature class foreach (var fcDef in fcList) { _tables.Add(TableString(fcDef as TableDefinition)); } //Tables foreach (var def in tables) { _tables.Add(TableString(def as TableDefinition)); } //////Uncomment for just Feature class in Feature Datasets ////foreach (var fdsDef in fdsList) { //// IReadOnlyList<Definition> tableDefsInDataset = gdb.GetRelatedDefinitions(fdsDef, //// DefinitionRelationshipType.DatasetInFeatureDataset); //// foreach (var def in tableDefsInDataset) { //// if (def.DatasetType == DatasetType.FeatureClass) //// _tables.Add(TableString(def as TableDefinition)); //// } ////} } } return(0); }); } finally { _timer.Stop(); if (_tables.Count > 0) { SelectedTableName = _tables[0]; } else { MessageBox.Show("No tables or feature datasets read", _gdbPath); } _executeQuery = false; OnPropertyChanged("IsExecutingQuery"); } }
/// <summary> /// Asynchronously creates an <see cref="ODataAsynchronousWriter" /> to write an async response. /// </summary> /// <returns>A running task for the created writer.</returns> /// <remarks>The write must flush the output when it's finished (inside the last Write call).</remarks> internal override Task <ODataAsynchronousWriter> CreateODataAsynchronousWriterAsync() { this.AssertAsynchronous(); return(TaskUtils.GetTaskForSynchronousOperation(() => this.CreateODataAsynchronousWriterImplementation())); }
public async Task WriteInStreamError_APIsShouldYieldSameResult() { var nestedWriterSettings = new ODataMessageWriterSettings { Version = ODataVersion.V4, EnableMessageStreamDisposal = false }; nestedWriterSettings.SetServiceDocumentUri(new Uri(ServiceUri)); var asyncException = await Assert.ThrowsAsync <ODataException>(async() => { IODataResponseMessage asyncResponseMessage = new InMemoryMessage { StatusCode = 200, Stream = this.asyncStream }; using (var messageWriter = new ODataMessageWriter(asyncResponseMessage, writerSettings)) { // Call to CreateODataAsynchronousWriterAsync triggers setting of output in-stream error listener var asynchronousWriter = await messageWriter.CreateODataAsynchronousWriterAsync(); var responseMessage = await asynchronousWriter.CreateResponseMessageAsync(); responseMessage.StatusCode = 200; // Next section added is to demonstrate that what was already written is flushed to the buffer before exception is thrown using (var nestedMessageWriter = new ODataMessageWriter(responseMessage, nestedWriterSettings)) { var writer = await nestedMessageWriter.CreateODataResourceWriterAsync(); } await messageWriter.WriteErrorAsync( new ODataError { ErrorCode = "NRE", Message = "Object reference not set to an instance of an object." }, /*includeDebugInformation*/ true); } }); this.asyncStream.Position = 0; var asyncResult = await new StreamReader(this.asyncStream).ReadToEndAsync(); var syncException = await Assert.ThrowsAsync <ODataException>( () => TaskUtils.GetTaskForSynchronousOperation(() => { IODataResponseMessage syncResponseMessage = new InMemoryMessage { StatusCode = 200, Stream = this.syncStream }; using (var messageWriter = new ODataMessageWriter(syncResponseMessage, writerSettings)) { // Call to CreateODataAsynchronousWriterAsync triggers setting of output in-stream error listener var asynchronousWriter = messageWriter.CreateODataAsynchronousWriter(); var responseMessage = asynchronousWriter.CreateResponseMessage(); responseMessage.StatusCode = 200; // Next section is added to demonstrate that what was already written is flushed to the buffer before exception is thrown using (var nestedMessageWriter = new ODataMessageWriter(responseMessage, nestedWriterSettings)) { var writer = nestedMessageWriter.CreateODataResourceWriter(); } messageWriter.WriteError( new ODataError { ErrorCode = "NRE", Message = "Object reference not set to an instance of an object." }, /*includeDebugInformation*/ true); } })); this.syncStream.Position = 0; var syncResult = await new StreamReader(this.syncStream).ReadToEndAsync(); var expected = @"HTTP/1.1 200 OK OData-Version: 4.0 Content-Type: application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false;charset=utf-8 "; Assert.Equal(Strings.ODataAsyncWriter_CannotWriteInStreamErrorForAsync, asyncException.Message); Assert.Equal(Strings.ODataAsyncWriter_CannotWriteInStreamErrorForAsync, syncException.Message); Assert.Equal(expected, asyncResult); Assert.Equal(expected, syncResult); }
/// <summary> /// Asynchronously create a <see cref="ODataBatchReader"/>. /// </summary> /// <param name="batchBoundary">The batch boundary to use.</param> /// <returns>Task which when completed returns the newly created <see cref="ODataCollectionReader"/>.</returns> internal override Task <ODataBatchReader> CreateBatchReaderAsync(string batchBoundary) { // Note that the reading is actually synchronous since we buffer the entire input when getting the stream from the message. return(TaskUtils.GetTaskForSynchronousOperation(() => this.CreateBatchReaderImplementation(batchBoundary, /*synchronous*/ false))); }
public Task EndRequest(IDotvvmRequestContext context, Exception exception) { return(TaskUtils.GetCompletedTask()); }
public virtual Task <int> DeleteAsync(Row row, IDataStoreKey key = null) { CheckServiceActive(); return(TaskUtils.AsCompletedTask(() => Delete(row))); }