IEnumerator CoroutineLoadResource(string resourcePath, ResourceResponse responseHandler, string requestIdentify) { DateTime requestTime = DateTime.Now; AssetBundleCreateRequest assetBundleAsyncOp; using (FileStream fileStream = File.Open(resourcePath, FileMode.Open)) { byte[] bytes = new byte[fileStream.Length]; fileStream.Read(bytes, 0, Convert.ToInt32(fileStream.Length)); assetBundleAsyncOp = AssetBundle.CreateFromMemory(bytes); } while (!assetBundleAsyncOp.isDone) yield return null; yield return assetBundleAsyncOp; Debug.Log(DateTime.Now.Subtract(requestTime)); try { responseHandler(assetBundleAsyncOp.assetBundle.mainAsset, null, requestIdentify); assetBundleAsyncOp.assetBundle.Unload(false); } catch (System.Exception e) { Debug.Log(string.Format("{0}\n{1}", e.Message, e.StackTrace)); } }
public override void ReadFile(string url, ResourceResponse response) { #if COHERENT_UNITY_UNSUPPORTED_PLATFORM throw new ApplicationException("Coherent UI doesn't support the target platform!"); #else string cleanUrl = GetFilepath(url); if (!File.Exists(cleanUrl)) { response.SignalFailure(); return; } byte[] bytes = File.ReadAllBytes(cleanUrl); IntPtr buffer = response.GetBuffer((uint)bytes.Length); if (buffer == IntPtr.Zero) { response.SignalFailure(); return; } Marshal.Copy(bytes, 0, buffer, bytes.Length); response.SignalSuccess(); #endif }
public void Request(string resourcePath, ResourceResponse responseHandler) { Object obj = Resources.Load(resourcePath); if (obj == null) responseHandler(null, string.Format("No such resource \"{0}\" in Resources."), resourcePath); else responseHandler(obj, null, resourcePath); }
public void Request(string resourcePath, ResourceResponse responseHandler) { responseHandler += AddToCachedPool; if (!_cachedResources.ContainsKey(resourcePath)) _resourceLoader.Request(resourcePath, responseHandler); else responseHandler(_cachedResources[resourcePath], null, resourcePath); }
IEnumerator CoroutineLoadResource(string resourcePath, ResourceResponse responseHandler) { DateTime requestTime = DateTime.Now; string requestResourcePath = string.Empty; if (resourcePath.IndexOf("file://") < 0) requestResourcePath = resourcePath.Insert(0, "file://"); WWW www = new WWW(requestResourcePath); yield return www; Debug.Log(DateTime.Now.Subtract(requestTime)); try { responseHandler(www.assetBundle.mainAsset, www.error, resourcePath); www.assetBundle.Unload(false); } catch (System.Exception e) { Debug.Log(string.Format("{0}\n{1}", e.Message, e.StackTrace)); } }
/// <summary> /// Executes the async document db call and logs document db specific information to ULS. /// </summary> /// <param name="tagId">ULS tag. Should be auto generated by git tagger, no need to specify.</param> /// <param name="documentdbFunc">Document db delegate that returns a Resource ie. Document, Collection, Database etc.</param> /// <param name="caller">Caller function name. No need to specify explicitly, will be set automatically on run time.</param> /// <returns>The ResourceResponse of type T.</returns> public static Task <ResourceResponse <T> > ExecuteAndLogAsync <T>( uint tagId, Func <Task <ResourceResponse <T> > > documentdbFunc, [CallerMemberName] string caller = null) where T : Resource, new() { return(ExecuteAndLogAsync <ResourceResponse <T> >( tagId, async() => { ResourceResponse <T> response = await documentdbFunc().ConfigureAwait(false); try { LogInfo( caller, response.ActivityId, response.RequestCharge, (int)response.StatusCode, response.ContentLocation, tagId); } catch (Exception) { } return response; }, caller)); }
private static async Task SendScheduleInterviewMessage(IDialogContext context, string name, string reqId) { OfficeDev.Talent.Management.InterviewRequest request = new OfficeDev.Talent.Management.InterviewRequest { Candidate = new OfficeDev.Talent.Management.CandidatesDataController().GetCandidateByName(name), Date = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day), PositionTitle = new OfficeDev.Talent.Management.OpenPositionsDataController().GetPositionForReqId(reqId).Title, Remote = false, ReqId = reqId }; IMessageActivity reply = context.MakeMessage(); reply.Attachments = new List <Attachment>(); reply.Text = $"Here's your request to schedule an interview:"; O365ConnectorCard card = CardHelper.CreateCardForInterviewRequest(request); reply.Attachments.Add(card.ToAttachment()); ConnectorClient client = new ConnectorClient(new Uri(context.Activity.ServiceUrl)); ResourceResponse resp = await client.Conversations.ReplyToActivityAsync((Activity)reply); }
public override ResourceResponse Put(ResourceRequestContext context) { var certGenerator = CertificateResourceHelpers.GetCertificateGeneratorInstance(context.BridgeConfiguration); string serialNumber; lock (s_certificateResourceLock) { if (context.Properties.TryGetValue(revokeSerialNumberKeyName, out serialNumber) && !string.IsNullOrWhiteSpace(serialNumber)) { certGenerator.RevokeCertificateBySerialNumber(serialNumber); } ResourceResponse response = new ResourceResponse(); response.Properties.Add(crlUriKeyName, certGenerator.CrlUri); response.Properties.Add( revokedCertificatesKeyName, string.Join <string>(",", certGenerator.RevokedCertificates)); return(response); } }
private static async Task ReplaceDoc(List <customer> pitem) { try { foreach (customer citem in pitem) { citem.CustomerName += DateTime.Now.ToString(); ResourceResponse <Document> cxResponse = await m_DC.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(m_szDatabaseName, m_szCollectionName, citem.Id), citem, new RequestOptions { PartitionKey = new PartitionKey(citem.Region) }); Logging.LogStats(string.Format(ErrMessage.RequestDiagString, cxResponse.RequestDiagnosticsString.ToString())); Logging.LogStats(string.Format(ErrMessage.RequestLatencyStats, cxResponse.RequestLatency.ToString())); Logging.LogStats(string.Format(ErrMessage.RequestChargeStats, cxResponse.RequestCharge.ToString())); } } catch (DocumentClientException dex) { Logging.LogException(dex); } catch (Exception ex) { Logging.LogException(ex); } }
public void Update(TData data) { Logger.LogDebug("Updating data in the Azure database", "AzureDocumentDbDataStore\\Update"); try { Logger.LogDebug("Getting existing document from the Azure database", "AzureDocumentDbDataStore\\Update"); DateTime start = DateTime.Now; Document documentToUpdate = AzureDocumentDbClient.CreateDocumentQuery(AzureDocumentDbCollection.DocumentsLink) .Where(d => d.Id == data.id) .AsEnumerable() .Single(); DateTime mid = DateTime.Now; Logger.LogDebug(string.Format("Getting existing document from the Azure database took {0}", mid - start), "AzureDocumentDbDataStore\\Update"); Logger.LogDebug("Replacing existing document in the Azure database", "AzureDocumentDbDataStore\\Update"); ResourceResponse <Document> result = AzureDocumentDbHelper.ExecuteFaultTollerantFunction(() => AzureDocumentDbClient.ReplaceDocumentAsync(documentToUpdate.SelfLink, data).Result); DateTime end = DateTime.Now; Logger.LogDebug(string.Format("Replacing existing document in the Azure database took {0} and cost:r\n{1}", end - mid, result), "AzureDocumentDbDataStore\\Update"); } finally { Logger.LogDebug("Updating data in the Azure database... Done", "AzureDocumentDbDataStore\\Update"); } }
async Task <TSaga> PreInsertSagaInstance <T>(ConsumeContext <T> context, TSaga instance) where T : class { try { ResourceResponse <Document> response = await _client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(_databaseName, _collectionName), instance, _requestOptions, true).ConfigureAwait(false); _log.DebugFormat("SAGA:{0}:{1} Insert {2}", TypeMetadataCache <TSaga> .ShortName, instance.CorrelationId, TypeMetadataCache <T> .ShortName); return(JsonConvert.DeserializeObject <TSaga>(response.Resource.ToString(), _jsonSerializerSettings)); } catch (Exception ex) { if (_log.IsDebugEnabled) { _log.DebugFormat("SAGA:{0}:{1} Dupe {2} - {3}", TypeMetadataCache <TSaga> .ShortName, instance.CorrelationId, TypeMetadataCache <T> .ShortName, ex.Message); } } return(null); }
public override void ReadFile(string url, ResourceResponse response) { string cleanUrl = GetFilepath(url); if (!File.Exists(cleanUrl)) { response.SignalFailure(); return; } byte[] bytes = File.ReadAllBytes(cleanUrl); IntPtr buffer = response.GetBuffer((uint)bytes.Length); if (buffer == IntPtr.Zero) { response.SignalFailure(); return; } Marshal.Copy(bytes, 0, buffer, bytes.Length); response.SignalSuccess(); }
private ResourceResponse CreateResponseFromLocalContent(ResourceRequest request) { //Uncomment this once above functionality is complete string resourceName; string filePath; // this project embeds static HTML/JS/CSS/PNG files as resources // by translating the resource's relative file path like Resources\foo/bar.html // to a logical name like /www/foo/bar.html //resourceName = String.Concat("Content", request.Url.AbsolutePath); resourceName = request.Url.AbsolutePath; resourceName = resourceName.Replace('/', Path.DirectorySeparatorChar); resourceName = (resourceName.StartsWith(Path.DirectorySeparatorChar.ToString())) ? resourceName.TrimStart(new char[] { Path.DirectorySeparatorChar }) : resourceName; filePath = Path.GetFullPath(Path.Combine(TempFolder, resourceName)); // cache the resource to a temp file if if (!File.Exists(filePath)) { ExtractResourceToFile(resourceName, filePath); } return(ResourceResponse.Create(filePath)); }
public async Task IntegrationTest3_DomainLayer_UserRepository_CreateItemAsync_CreateDocumentAsyncIsCalled_ResponseCreated() { //arrange var document = new Document(); JObject jsobObj = JObject.FromObject(_testUserOne); document.LoadFrom(jsobObj.CreateReader()); _client.DefaultRequestHeaders.Add("username", _testUserOne.Username); _client.DefaultRequestHeaders.Add("password", _testUserOne.Password); var documentClientResponse = new ResourceResponse <Document>(document); var stringContent = new StringContent(JsonConvert.SerializeObject(_testUserOne), Encoding.UTF8, "application/json"); _fakeDbContext.DocumentClient.CreateDocumentAsync(Arg.Any <Uri>(), Arg.Any <IUser>()).Returns(Task.FromResult(documentClientResponse)); //act var response = await _client.PostAsync("api/User", stringContent); //assert Assert.That(response.StatusCode, Is.EqualTo(System.Net.HttpStatusCode.Created)); }
/// <summary> /// Replaces the RetentionDuration of the ChangeFeedPolicy associated with the Cosmos DB collection /// </summary> /// <param name="databaseId">>Name of the Cosmos DB database</param> /// <param name="collectionId">Name of the Cosmos DB collection</param> /// <returns></returns> private async Task ReplaceDocumentCollectionAsync( string databaseId, string collectionId) { DocumentCollection collection = (await this.DocumentClient.ReadDocumentCollectionAsync(string.Format("/dbs/{0}/colls/{1}", databaseId, collectionId))).Resource; // Update the ChangeFeedPolicy RetentionDuration collection.ChangeFeedPolicy.RetentionDuration = TimeSpan.FromMinutes(10); try { ResourceResponse <DocumentCollection> replacedCollection = await this.DocumentClient.ReplaceDocumentCollectionAsync(collection); Console.WriteLine("Replaced the ChangeFeedPolicy RetentionDuration for the collection.\n"); } catch (DocumentClientException ex) { Console.WriteLine("DocumentClientException thrown when attempting to replace the collection's ChangeFeedPolicy RetentionDuration. Original exception was: {0}", ex.Message); } catch (Exception ex) { Console.WriteLine("Exception thrown when attempting to replace the collection's ChangeFeedPolicy RetentionDuration. Original exception was: {0}", ex.Message); } }
public async Task DeleteGamesAsync(GamesModel games) { AssertEntity(games); try { GamesModel deletedDocument = null; ResourceResponse <Document> response = await _documentClient.DeleteDocumentAsync(CreateDocumentUri(games.Id)); if (response.StatusCode == HttpStatusCode.OK) { deletedDocument = (GamesModel)(dynamic)response.Resource; } else { Trace.TraceWarning($"Document not deleted: response code {response.StatusCode}"); } } catch (Exception ex) { Trace.TraceError($"ERROR DELETING DOCUMENT: {ex}"); } }
public async Task PrepareAsync() { if (this.initialized) { return; } Uri containerUri = UriFactory.CreateDocumentCollectionUri(this.databsaeName, this.containerName); ResourceResponse <Document> itemResponse = await this.documentClient.CreateDocumentAsync( containerUri, this.sampleJObject, new RequestOptions() { PartitionKey = new PartitionKey(this.executionItemPartitionKey) }); if (itemResponse.StatusCode != HttpStatusCode.Created) { throw new Exception($"Create failed with statuscode: {itemResponse.StatusCode}"); } this.initialized = true; }
private static async Task CreateDoc() { try { for (int icount = 1; icount <= m_maxdoccount; icount++) { customer citem = GetCustomerDoc(icount); ResourceResponse <Document> cxResponse = await m_DC.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(m_szDatabaseName, m_szCollectionName), citem, new RequestOptions { PartitionKey = new PartitionKey(citem.Region) }); Logging.LogStats(string.Format(ErrMessage.RequestDiagString, cxResponse.RequestDiagnosticsString.ToString())); Logging.LogStats(string.Format(ErrMessage.RequestLatencyStats, cxResponse.RequestLatency.ToString())); Logging.LogStats(string.Format(ErrMessage.RequestChargeStats, cxResponse.RequestCharge.ToString())); } } catch (DocumentClientException dex) { Logging.LogException(dex); } catch (Exception ex) { Logging.LogException(ex); } }
public async Task RemoveByIdRemoves() { // Arrange var id = Guid.NewGuid().ToString(); var addedDummy = new Dummy { Id = id, Name = "Test" }; var response = new ResourceResponse <Document>(new Document { Id = addedDummy.Id }); _mockDocumentClient.Setup(x => x.DeleteDocumentAsync(It.IsAny <string>(), null)) .ReturnsAsync(response); var entityStore = new CosmosStore <Dummy>(_mockDocumentClient.Object, "databaseName", new CosmosDatabaseCreator(_mockDocumentClient.Object), new CosmosCollectionCreator(_mockDocumentClient.Object)); // Act var result = await entityStore.RemoveByIdAsync(id); // Assert Assert.Equal(CosmosOperationStatus.Success, result.CosmosOperationStatus); }
/// <summary> /// Sends activities to the conversation. /// </summary> /// <param name="context">The context object for the turn.</param> /// <param name="activities">The activities to send.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <remarks>If the activities are successfully sent, the task result contains /// an array of <see cref="ResourceResponse"/> objects containing the IDs that /// the receiving channel assigned to the activities.</remarks> /// <seealso cref="ITurnContext.OnSendActivities(SendActivitiesHandler)"/> public override async Task <ResourceResponse[]> SendActivities(ITurnContext context, Activity[] activities) { List <ResourceResponse> responses = new List <ResourceResponse>(); foreach (var activity in activities) { ResourceResponse response; if (activity.Type == ActivityTypesEx.Delay) { // The Activity Schema doesn't have a delay type build in, so it's simulated // here in the Bot. This matches the behavior in the Node connector. int delayMs = (int)activity.Value; await Task.Delay(delayMs).ConfigureAwait(false); // In the case of a Delay, just create a fake one. Match the incoming activityId if it's there. response = new ResourceResponse(activity.Id ?? string.Empty); } else if (activity.Type == "invokeResponse") // Aligning name with Node { context.Services.Add <Activity>(InvokeReponseKey, activity); // In the case of Invoke, just create a fake one. Match the incoming activityId if it's there. response = new ResourceResponse(activity.Id ?? string.Empty); } else { var connectorClient = context.Services.Get <IConnectorClient>(); response = await connectorClient.Conversations.SendToConversationAsync(activity).ConfigureAwait(false); } // Collect all the responses that come from the service. responses.Add(response); } return(responses.ToArray()); }
public async Task GetAsyncTest() { var collectionId = rand.NextString(); var key = rand.NextString(); var data = rand.NextString(); var etag = rand.NextString(); var timestamp = rand.NextDateTimeOffset(); var document = new Document(); document.SetPropertyValue("CollectionId", collectionId); document.SetPropertyValue("Key", key); document.SetPropertyValue("Data", data); document.SetETag(etag); document.SetTimestamp(timestamp); var response = new ResourceResponse <Document>(document); mockClient .Setup(x => x.ReadDocumentAsync( It.IsAny <string>(), It.IsAny <RequestOptions>())) .ReturnsAsync(response); var result = await container.GetAsync(collectionId, key); Assert.Equal(result.CollectionId, collectionId); Assert.Equal(result.Key, key); Assert.Equal(result.Data, data); Assert.Equal(result.ETag, etag); Assert.Equal(result.Timestamp, timestamp); mockClient .Verify(x => x.ReadDocumentAsync( It.Is <string>(s => s == $"{mockCollectionLink}/docs/{collectionId.ToLowerInvariant()}.{key.ToLowerInvariant()}"), It.IsAny <RequestOptions>()), Times.Once); }
public static async Task <ResourceResponse <DocumentCollection> > HandleCollectionFeedInsertAsync(IDocumentClient client, string collectionName, IndexingPolicy indexingPolicy, RequestOptions requestOption, CancellationToken cancellationToken) { await ThrowIfCollectionExists(client, collectionName); RequestOptions requestOptions = requestOption; if ((requestOptions == null || !requestOptions.OfferThroughput.HasValue) && !(await IsSharedThroughputEnabledAsync(client))) { if (requestOption == null) { requestOption = new RequestOptions(); } requestOption.OfferThroughput = 800; } ResourceResponse <DocumentCollection> collectionResponse2 = null; try { collectionResponse2 = await CreateDocumentCollectionAsync(collectionName, client, indexingPolicy, requestOption); } catch (DocumentClientException ex) { if (ex.StatusCode != HttpStatusCode.NotFound) { Exception obj = ex as Exception; if (obj == null) { throw ex; } ExceptionDispatchInfo.Capture(obj).Throw(); } await CreateTablesDB(client); collectionResponse2 = await CreateDocumentCollectionAsync(collectionName, client, indexingPolicy, requestOption); } return(collectionResponse2); }
public async Task StartAsync(IDialogContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (!string.IsNullOrEmpty(context.Activity.ReplyToId)) { Activity activity = context.Activity as Activity; updateCounter = TemplateUtility.ParseUpdateCounterJson(activity); var updatedMessage = CreateUpdatedMessage(context); ConnectorClient client = new ConnectorClient(new Uri(context.Activity.ServiceUrl)); try { ResourceResponse resp = await client.Conversations.UpdateActivityAsync(context.Activity.Conversation.Id, context.Activity.ReplyToId, (Activity)updatedMessage); await context.PostAsync(Strings.UpdateCardMessageConfirmation); } catch (Exception ex) { await context.PostAsync(Strings.ErrorUpdatingCard + ex.Message); } } else { await context.PostAsync(Strings.NoMsgToUpdate); } context.Done <object>(null); //Set the Last Dialog in Conversation Data context.UserData.SetValue(Strings.LastDialogKey, Strings.LastDialogSetupUpdateCard); }
public static async Task <string> UpdateTDMStatus(string REQID, Models.TDMStatus tdmstatus, TraceWriter log) { log.Info("Entered UpdateTDMStatus"); string endpointUrl = ConfigurationManager.AppSettings["Azure.CosmosDb.Url"].ToString(); string primaryKey = ConfigurationManager.AppSettings["Azure.CosmosDb.Key"].ToString(); string databaseName = ConfigurationManager.AppSettings["Azure.CosmosDb.Name"].ToString(); string collectionName = ConfigurationManager.AppSettings["Azure.CosmosDb.Collection"].ToString(); DocumentClient client = new DocumentClient(new Uri(endpointUrl), primaryKey); //client.ReadDocumentAsync() Models.TDMStatus cosmosdoc; //Document cosmosdoc; // Get record cosmosdoc = client.CreateDocumentQuery <Models.TDMStatus>( UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), new FeedOptions { EnableCrossPartitionQuery = true }) .Where(m => m.REQID == REQID) .AsEnumerable() .FirstOrDefault(); cosmosdoc.REQID = tdmstatus.REQID; cosmosdoc.TDMLOC = tdmstatus.TDMLOC; cosmosdoc.ROBID = tdmstatus.ROBID; cosmosdoc.OPSTATUS = tdmstatus.OPSTATUS; cosmosdoc.CASEFILERTRSTATUS = tdmstatus.CASEFILERTRSTATUS; cosmosdoc.DELSTATUS = tdmstatus.DELSTATUS; ResourceResponse <Document> response = await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, cosmosdoc.id), cosmosdoc); return("Completed Update. Charge:" + response.RequestCharge); //return await Task.FromResult(TDMStatusList); }
public override async Task <ResourceResponse[]> SendActivitiesAsync( ITurnContext turnContext, Activity[] activities, CancellationToken cancellationToken ) { var responses = new ResourceResponse[activities.Length]; for (int idx = 0; idx < activities.Length; idx++) { var activity = activities[idx]; switch (activity.Type) { case ActivityTypes.Message: { IMessageActivity msg = activity.AsMessageActivity(); await Rest.Chat.PostMessage( new Message { Channel = msg.Conversation.Id, Text = msg.Text } ); } break; default: throw new NotImplementedException(); } responses[idx] = new ResourceResponse(activity.Id); } return(responses); }
private static void PrintSummaryStats(ResourceResponse <DocumentCollection> collection, List <PartitionKeyRange> partitionKeyRanges) { Console.WriteLine("Summary: {0}", collection.CurrentResourceQuotaUsage); Console.WriteLine("\tpartitions: {0}", partitionKeyRanges.Count); string[] keyValuePairs = collection.CurrentResourceQuotaUsage.Split(';'); foreach (string kvp in keyValuePairs) { string metricName = kvp.Split('=')[0]; string metricValue = kvp.Split('=')[1]; switch (metricName) { case "collectionSize": break; case "documentsSize": Console.WriteLine("\t{0}: {1} GB", metricName, Math.Round(int.Parse(metricValue) / (1024 * 1024.0), 3)); break; case "documentsCount": Console.WriteLine("\t{0}: {1:n0}", metricName, int.Parse(metricValue)); break; case "storedProcedures": case "triggers": case "functions": break; default: Console.WriteLine("\t{0}: {1}", metricName, metricValue); break; } } Console.WriteLine(); }
public async Task <TSaga> GetSaga <TSaga>(Guid correlationId, bool useJsonSerializerSettings) where TSaga : class, IVersionedSaga { try { RequestOptions options = null; JsonSerializerSettings serializerSettings = null; if (useJsonSerializerSettings) { options = new RequestOptions(); serializerSettings = GetSagaRenameSettings <TSaga>(); options.JsonSerializerSettings = serializerSettings; } ResourceResponse <Document> document = await Client.ReadDocumentAsync(UriFactory.CreateDocumentUri(DatabaseName, CollectionName, correlationId.ToString()), options); return(JsonConvert.DeserializeObject <TSaga>(document.Resource.ToString(), serializerSettings)); } catch (DocumentClientException e) when(e.StatusCode == System.Net.HttpStatusCode.NotFound) { return(null); } }
private static void Main(string[] args) { string docId = Guid.NewGuid().ToString(); string attId = Guid.NewGuid().ToString(); var myDoc = new { id = docId, Name = "Max", City = "Aberdeen" }; // this is the document you are trying to save var client = GetClientAsync().GetAwaiter().GetResult(); var createUrl = UriFactory.CreateDocumentCollectionUri("mytestdb", "test"); ResourceResponse <Document> document = client.CreateDocumentAsync(createUrl, myDoc).GetAwaiter().GetResult(); // Measure the performance (request units) of writes // ResourceResponse<Document> response = await client.CreateDocumentAsync(collectionSelfLink, myDocument); Console.WriteLine("Insert of document consumed {0} request units", document.RequestCharge); // Measure the performance (request units) of queries IDocumentQuery <dynamic> queryable = client.CreateDocumentQuery( UriFactory.CreateDocumentCollectionUri("mytestdb", "test"), "select top 1 * from c").AsDocumentQuery(); FeedResponse <dynamic> queryResponse = queryable.ExecuteNextAsync <dynamic>().GetAwaiter().GetResult(); Console.WriteLine("Query batch consumed {0} request units", queryResponse.RequestCharge); Console.Read(); }
private static async Task UpsertDocumentAsync() { Console.WriteLine("\n1.6 - Upserting a document"); var upsertOrder = GetSalesOrderSample("SalesOrder3"); ResourceResponse <Document> response = await client.UpsertDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), upsertOrder); var upserted = response.Resource; Console.WriteLine("Request charge of upsert operation: {0}", response.RequestCharge); Console.WriteLine("StatusCode of this operation: {0}", response.StatusCode); Console.WriteLine("Id of upserted document: {0}", upserted.Id); Console.WriteLine("AccountNumber of upserted document: {0}", upserted.GetPropertyValue <string>("AccountNumber")); upserted.SetPropertyValue("AccountNumber", "updated account number"); response = await client.UpsertDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), upserted); upserted = response.Resource; Console.WriteLine("Request charge of upsert operation: {0}", response.RequestCharge); Console.WriteLine("StatusCode of this operation: {0}", response.StatusCode); Console.WriteLine("Id of upserted document: {0}", upserted.Id); Console.WriteLine("AccountNumber of upserted document: {0}", upserted.GetPropertyValue <string>("AccountNumber")); }
public static async Task <IActionResult> delete_device( [HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "devices/{device_id}")] HttpRequest request, string device_id, ILogger log) // { var option = new FeedOptions { EnableCrossPartitionQuery = true }; DeviceItem device_to_delete = Resources.docClient.CreateDocumentQuery <DeviceItem>( UriFactory.CreateDocumentCollectionUri("waterly_db", "waterly_devices"), option) .Where(device_to_delete => device_to_delete.id.Equals(device_id)) .AsEnumerable() .First(); //swipe boolean status device_to_delete.status = false; ResourceResponse <Document> response = await Resources.docClient.ReplaceDocumentAsync( UriFactory.CreateDocumentUri("waterly_db", "waterly_devices", device_to_delete.id), device_to_delete); var updated = response.Resource; return(new OkObjectResult(device_to_delete)); }
/// <summary> /// Returns a document from the documentDB by the given id. /// This method also returns soft deleted items if requested. /// </summary> /// <param name="collectionName">Name of the collection on which the operation must be performed.</param> /// <param name="id">The id of the object to return.</param> /// <param name="partition">The partition of the object to return.</param> /// <param name="doTraceWriting">When an exception is raised, it will be written to the tracing. Setting this parameter /// false will prevent the tracewriting.</param> /// <returns>The object or <c>null</c> if not exists.</returns> public async Task <Document> GetById(string collectionName, string id, string partition, bool doTraceWriting = true) { try { Uri uri = CreateDocumentLink(collectionName, id); ResourceResponse <Document> response = await _client.ReadDocumentAsync(uri); //ResourceResponse<Document> response = await _client.ReadDocumentAsync(uri, GetRequestOptions(partition)); return(response.Resource); } catch (DocumentClientException documentClientException) { if (doTraceWriting) { _trace.TraceWarning(ErrorCodes.DBDocumentNotFound, collectionName, id, partition); } if (documentClientException.StatusCode == HttpStatusCode.NotFound) { return(null); } throw; } }
public override string CreateExpiredJob(Common.Job job, IDictionary <string, string> parameters, DateTime createdAt, TimeSpan expireIn) { if (job == null) { throw new ArgumentNullException(nameof(job)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } InvocationData invocationData = InvocationData.Serialize(job); Entities.Job entityJob = new Entities.Job { InvocationData = invocationData, Arguments = invocationData.Arguments, CreatedOn = createdAt, ExpireOn = createdAt.Add(expireIn), Parameters = parameters.Select(p => new Parameter { Name = p.Key, Value = p.Value }).ToArray() }; ResourceResponse <Document> response = Storage.Client.CreateDocumentWithRetriesAsync(Storage.Collections.JobDocumentCollectionUri, entityJob).GetAwaiter().GetResult(); if (response.StatusCode == HttpStatusCode.Created || response.StatusCode == HttpStatusCode.OK) { return(entityJob.Id); } return(string.Empty); }
public async Task <IHttpActionResult> Post(HouseDto houseDto) { // get a standard DocumentDB client await EnsureClientIsConnected(); // convert the DTO into the Document type var houseDoc = JsonConvert.DeserializeObject <HouseDocument>(JsonConvert.SerializeObject(houseDto)); // DocumentDB Triggers are "opt-in", so opt-in var docdbOptions = new RequestOptions(); docdbOptions.PreTriggerInclude = new List <string> { "MaintainHistoryAndTimestamps" }; // execute the create document call safely with retries ResourceResponse <Document> created = null; try { created = await DocumentDbExtensions.ExecuteResultWithRetryAsync(() => client.CreateDocumentAsync(collectionLink, houseDoc, docdbOptions)); } catch (DocumentDbNonRetriableResponse e) { return(StatusCode((e.InnerException as DocumentClientException).StatusCode ?? HttpStatusCode.InternalServerError)); } // get the resulting document (it is returned above, but in non-typed form - probably should really be using AutoMapper or something like that here) var result = await DocumentDbExtensions.ExecuteQueryWithContinuationAndRetryAsync( client.CreateDocumentQuery <HouseDto>(collectionLink) .Where(x => x.DocumentType == DocumentType.House) .Where(x => x.Id == created.Resource.Id)); return(Created(result.Single())); }
public async Task <Document> CreateOrReplaceDocumentAsync(string databaseName, string collectionName, Node root = null) { if (root != null) { rootNode.RootNode = root; } using (var client = new DocumentClient(new Uri(Settings.Default.DocumentDBURI), Settings.Default.DocumentDBPrimaryKey)) { try { ResourceResponse <Document> response = await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), rootNode); return(response.Resource); } catch (DocumentClientException de) { if (de.StatusCode == HttpStatusCode.Conflict) { string documentLink = "/dbs/" + Settings.Default.DocumenDBDatabaseName + "/colls/" + Settings.Default.DocumentDBCollectionName + "/docs/" + Settings.Default.HierarchyDocument; //ResourceResponse<Document> response = await client.ReplaceDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), rootNode); ResourceResponse <Document> response = await client.ReplaceDocumentAsync(documentLink, rootNode); return(response.Resource); } else { throw de; } } catch (Exception e) { throw e; } } }
public override void ReadFile(string url, URLRequestBase request, ResourceResponse response) { #if COHERENT_UNITY_UNSUPPORTED_PLATFORM throw new ApplicationException("Coherent UI doesn't support the target platform!"); #else string cleanUrl = GetFilepath(url); if (!File.Exists(cleanUrl)) { response.SignalFailure(); return; } if (request.GetExtraHeaderIndex("Range") < 0) { DoCompleteRead(cleanUrl, request, response); } else { DoPartialRead(cleanUrl, request, response); } #endif }
// POST: api/AzureBlobItem public async Task <HttpResponseMessage> Post([FromBody] string jsonContent) { if (client == null) { client = new DocumentClient(new Uri(endpointUrl), authorizationKey); } AzureDocumentDbCrudHelper.Init(client, databaseId, collectionId); var collectionLink = UriFactory.CreateDocumentCollectionUri(databaseId, collectionId); //Create a dynamic object, //Notice the case here. The properties will be created in the database //with whatever case you give the property //If you read this back in to a Document object id will get mapped to Id dynamic dynamicJObject = JObject.Parse(jsonContent); ResourceResponse <Document> response = await client.CreateDocumentAsync(collectionLink, dynamicJObject); var createdDocument = response.Resource; //AzureDocumentDbCrudHelper return(Request.CreateResponse(HttpStatusCode.OK, new { createdDocumentId = createdDocument.Id, responseRequestCharge = response.RequestCharge })); }
public async Task <T> Create <T>(T data) where T : Entities.PartitionedEntry { Guard.AgainstNull(nameof(data), data); Guard.AgainstNullOrWhitespace(nameof(data.PartitionId), data.PartitionId); if (string.IsNullOrWhiteSpace(data.id)) { data.id = Guid.NewGuid().ToString(); } await this.EnsureInitialized(); string collectionLink = UriFactory.CreateDocumentCollectionUri(this.databaseName, this.collectionName).ToString(); ResourceResponse <Document> result = await this.client.CreateDocumentAsync( collectionLink, data, new RequestOptions() { PartitionKey = new PartitionKey(data.PartitionId) }); return(data); }
private void DoPartialRead(string cleanUrl, URLRequestBase request, ResourceResponse response) { string rangeValue = request.GetExtraHeader("Range"); Match match = m_RangeRequestValue.Match (rangeValue); if (!match.Success) { response.SignalFailure(); return; } long fileSize = new FileInfo(cleanUrl).Length; long startByte = long.Parse (match.Groups ["From"].Value); string endByteString = match.Groups ["To"].Value; long endByte = fileSize - 1; if (string.IsNullOrEmpty(endByteString)) { // Clamp to a maximum chunk size const long MaxPartialReadSize = 16 * 1024 * 1024; if (endByte - startByte > MaxPartialReadSize) { endByte = startByte + MaxPartialReadSize; } } else { endByte = long.Parse(endByteString); } // Clamp to int.MaxValue since that's the type BinaryReader // allows us to read; if it could read more bytes, then we would // clamp the size to uint.MaxValue since ResourceResponse.GetBuffer // expects an uint value. long bufferSize = Math.Min((long)int.MaxValue, endByte - startByte + 1); byte[] bytes = new byte[bufferSize]; using (BinaryReader reader = new BinaryReader( new FileStream(cleanUrl, FileMode.Open))) { reader.BaseStream.Seek(startByte, SeekOrigin.Begin); reader.Read(bytes, 0, (int)bufferSize); } IntPtr buffer = response.GetBuffer((uint)bytes.Length); if (buffer == IntPtr.Zero) { response.SignalFailure(); return; } Marshal.Copy(bytes, 0, buffer, bytes.Length); // Set required response headers response.SetStatus(206); response.SetResponseHeader("Accept-Ranges", "bytes"); response.SetResponseHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + fileSize); response.SetResponseHeader("Content-Length", bufferSize.ToString()); response.SignalSuccess(); }
public void Request(string resourcePath, ResourceResponse responseHandler) { CoroutineManager.Instance.StartCoroutine(CoroutineLoadResource(resourcePath, responseHandler, resourcePath)); }
private void DoCompleteRead(string cleanUrl, URLRequestBase request, ResourceResponse response) { byte[] bytes = File.ReadAllBytes(cleanUrl); IntPtr buffer = response.GetBuffer((uint)bytes.Length); if (buffer == IntPtr.Zero) { response.SignalFailure(); return; } Marshal.Copy(bytes, 0, buffer, bytes.Length); response.SetStatus(200); response.SignalSuccess(); }