private Uri GetDocumentLink(string id)
 {
     return(UriFactory.CreateDocumentUri(_settings.DatabaseName, _settings.CollectionName, id));
 }
 public async Task <Document> UpdatePersonAsync(string id, T person)
 {
     return(await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), person));
 }
 public async Task <Document> UpdateItemAsync(string id, T item)
 {
     return(await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), item));
 }
Esempio n. 4
0
 private Uri DocUri(string id)
 {
     return(UriFactory.CreateDocumentUri(dbName, CollName, id));
 }
Esempio n. 5
0
        public static async Task DeleteItemAsync(string id)
        {
            await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id));

            //, new RequestOptions(){PartitionKey = new PartitionKey(id)});
        }
 Uri GetDocumentUri(string id)
 {
     return(UriFactory.CreateDocumentUri(_databaseId, _collectionId, id));
 }
Esempio n. 7
0
 public async Task DeleteAsync(string id)
 {
     await _client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(_databaseId, _collectionId, id)).ConfigureAwait(false);
 }
Esempio n. 8
0
 private Uri GetDocumentLink <T>(string id) where T : IDataDocument
 {
     return(UriFactory.CreateDocumentUri(databaseId, collectionId, id));
 }
Esempio n. 9
0
        public async Task Run()
        {
            WriteLine("1. Insert, pre trigger");
            WriteLine("2. Update, pre trigger");
            WriteLine("3. Create triggers");

            SPOption option = (SPOption)ProgramHelper.EnterInt("");

            switch (option)
            {
            case SPOption.InsertPreTrigger:
            {
                ZipModel model = new ZipModel()
                {
                    City  = "Sarajevo",
                    Pop   = 1854,
                    State = "BiH",
                    Loc   = new Point(43.8607994, 18.4018904),
                    Id    = "989898"
                };

                Document findZipModel = await _documentRepository.ReadDocumentByIdAsync <Document>(model.Id, UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId));

                if (findZipModel != null)
                {
                    await _documentRepository.DeleteDocument(DatabaseId, CollectionId, findZipModel.Id);
                }

                Document document = await _documentRepository.InsertDocument(DatabaseId, CollectionId, model, new RequestOptions { PreTriggerInclude = new[] { "setCreatedDate" } });

                Success("New document successfully created.");
                break;
            }

            case SPOption.ReplacePostTrigger:
            {
                ZipModel model = await _documentRepository.ReadDocumentByIdAsync <ZipModel>("989898", UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId));

                model.City = "Neum";

                ZipModel updatedModel = await _documentRepository.UpdateDocument <ZipModel>(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, model.Id), model, new RequestOptions { PreTriggerInclude = new[] { "setUpdatedDate" } });


                Success("Document with id >>> " + updatedModel.Id + " <<< updated.");
                Success("Created date time >>> " + updatedModel.CreatedDateTime.Value.ToString("MM/dd/yyyy hh:mm:ss tt") + " <<<.");
                Success("Updated date time >>> " + updatedModel.UpdatedDateTime.Value.ToString("MM/dd/yyyy hh:mm:ss tt") + " <<< updated.");
                break;
            }

            case SPOption.CreateTriggers:
            {
                Trigger setCreatedDate = new Trigger()
                {
                    Id               = "setCreatedDate",
                    Body             = File.ReadAllText(@"Scripts\trSetCreatedDate.js"),
                    TriggerOperation = TriggerOperation.Create,
                    TriggerType      = TriggerType.Pre
                };

                Trigger setUpdatedDate = new Trigger()
                {
                    Id               = "setUpdatedDate",
                    Body             = File.ReadAllText(@"Scripts\trSetUpdatedDate.js"),
                    TriggerOperation = TriggerOperation.Update,
                    TriggerType      = TriggerType.Pre
                };

                Trigger newCreatedTrigger = await _triggerRepository.CreateTriggerAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), setCreatedDate);

                WriteLine(string.Format("Created trigger {0}; RID: {1}", newCreatedTrigger.Id, newCreatedTrigger.ResourceId));

                Trigger newUpdatedTrigger = await _triggerRepository.CreateTriggerAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), setUpdatedDate);

                WriteLine(string.Format("Created trigger {0}; RID: {1}", newUpdatedTrigger.Id, newUpdatedTrigger.ResourceId));

                break;
            }
            }
        }
Esempio n. 10
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 public static async Task <Document> DeleteItemAsync(string id)
 {
     return(await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, typeof(T).Name, id)));
 }
Esempio n. 11
0
        /// <inheritdoc/>
        public async Task <Instance> Update(Instance item)
        {
            PreProcess(item);

            ResourceResponse <Document> createDocumentResponse = await Client
                                                                 .ReplaceDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, item.Id), item);

            Document document = createDocumentResponse.Resource;
            Instance instance = JsonConvert.DeserializeObject <Instance>(document.ToString());

            await PostProcess(instance);

            return(instance);
        }
Esempio n. 12
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="id"></param>
 /// <param name="item"></param>
 /// <returns></returns>
 public static async Task <Document> UpdateItemAsync(string id, T item)
 {
     return(await client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, typeof(T).Name, id), item));
 }
        public async Task <Boolean> ReplaceDocumentEntity(string databaseName, string entityName, string document, string idDocument)
        {
            var response = await this.client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseName, entityName, idDocument), JsonConvert.DeserializeObject(document));

            return(response.StatusCode == HttpStatusCode.OK);
        }
Esempio n. 14
0
        public async Task <IActionResult> CreateFromBaseKit(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)]
            HttpRequest req,
            [CosmosDB(databaseName: "2wr", collectionName: "emergencykits", ConnectionStringSetting = "CosmosDBConnection")]
            DocumentClient client,
            [CosmosDB(databaseName: "2wr", collectionName: "basekits", ConnectionStringSetting = "CosmosDBConnection")]
            DocumentClient baseKitClient,
            ILogger log)
        {
            log.LogInformation($"Creating a new kit off of a base kit");
            var authorizationResult = await _apiAuthentication.AuthenticateAsync(req.Headers);

            if (authorizationResult.Failed)
            {
                log.LogWarning(authorizationResult.FailureReason);
                return(new UnauthorizedResult());
            }

            Uri collectionUri = UriFactory.CreateDocumentCollectionUri("2wr", "emergencykits");

            var content = await new StreamReader(req.Body).ReadToEndAsync();
            var request = JsonConvert.DeserializeObject <CreateKitFromBaseRequest>(content);
            var kit     = new Kit();

            kit.Id     = Guid.NewGuid().ToString();
            kit.UserId = authorizationResult.User.Identity.Name;

            //Pull Base kit information by id, Add items from base kit, multiply quantity by the count
            var     baseKitUri = UriFactory.CreateDocumentUri("2wr", "basekits", request.BaseKitId);
            BaseKit baseKit    = null;

            try
            {
                baseKit = (await baseKitClient.ReadDocumentAsync <BaseKit>(baseKitUri, new RequestOptions {
                    PartitionKey = new PartitionKey(request.BaseKitId)
                })).Document;
            }
            catch (DocumentClientException ex)
            {
                if (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    log.LogWarning($"Base Kit: {request.BaseKitId} not found.");
                    return(new BadRequestObjectResult("Base Kit not found."));
                }
            }

            baseKit.Items.ForEach(bki => kit.Items.Add(new KitItem {
                Id               = Guid.NewGuid().ToString(),
                UserId           = authorizationResult.User.Identity.Name,
                Name             = bki.Name,
                Description      = bki.Description,
                Photo            = bki.Photo,
                Quantity         = bki.QuantityPerCount * request.Count,
                QuantityUnit     = bki.QuantityUnit,
                IsAvailableInKit = false
            }));

            Document document = await client.CreateDocumentAsync(collectionUri, kit);

            return(new OkObjectResult(kit));
        }
Esempio n. 15
0
        public async Task <ActionResult <Models.AppUser> > GetUserByDocumentId(string documentId)
        {
            try
            {
                Models.AppUser user = await _cosmosDBclient.ReadDocumentAsync <Models.AppUser>(UriFactory.CreateDocumentUri(
                                                                                                   _dbName, _collectionName, documentId));

                return(Ok(user));
            }
            catch (DocumentClientException de)
            {
                switch (de.StatusCode.Value)
                {
                case System.Net.HttpStatusCode.NotFound:
                    return(NotFound());
                }
            }
            return(BadRequest());
        }
Esempio n. 16
0
 static Uri CreateDocumentUri(string id) =>
 UriFactory.CreateDocumentUri(PersonModel.DatabaseId, PersonModel.CollectionId, id);
        /// <summary>
        /// Update instance for a given form id
        /// </summary>
        /// <param name="instanceId">the instance id</param>
        /// <param name="item">the instance</param>
        /// <returns>The instance</returns>
        public async Task <Instance> UpdateInstanceInCollectionAsync(Guid instanceId, Instance item)
        {
            ResourceResponse <Document> createDocumentResponse = await _client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseId, collectionId, instanceId.ToString()), item);

            Document document = createDocumentResponse.Resource;
            Instance instance = JsonConvert.DeserializeObject <Instance>(document.ToString());

            return(instance);
        }
 public static Uri CreateDocumentUri(Guid actionPlanId)
 {
     return(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, actionPlanId.ToString()));
 }
Esempio n. 19
0
        public async Task <T> UpdateAsync(string id, T item)
        {
            var result = await _client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(_databaseId, _collectionId, id), item).ConfigureAwait(false);

            return(JsonConvert.DeserializeObject <T>(result.Resource.ToString()));
        }
 public static Uri CreateCustomerDocumentUri(Guid customerId)
 {
     return(UriFactory.CreateDocumentUri(CustomerDatabaseId, CustomerCollectionId, customerId.ToString()));
 }
        private Uri GetDocumentUriForEntity(ToDo entity)
        {
            var documentUri = UriFactory.CreateDocumentUri(DatabaseName, CollectionName, entity.Id.ToString());

            return(documentUri);
        }
 public static Uri CreateInteractionDocumentUri(Guid interactionId)
 {
     return(UriFactory.CreateDocumentUri(InteractionDatabaseId, InteractionCollectionId, interactionId.ToString()));;
 }
Esempio n. 23
0
        public void TestStoredProcedure()
        {
            // Create a document client with a customer json serializer settings
            JsonSerializerSettings serializerSettings = new JsonSerializerSettings();

            serializerSettings.Converters.Add(new ObjectStringJsonConverter <SerializedObject>(_ => _.Name, _ => SerializedObject.Parse(_)));
            ConnectionPolicy connectionPolicy = new ConnectionPolicy {
                ConnectionMode = ConnectionMode.Gateway
            };
            ConsistencyLevel defaultConsistencyLevel = ConsistencyLevel.Session;
            DocumentClient   client = CreateDocumentClient(
                this.hostUri,
                this.masterKey,
                serializerSettings,
                connectionPolicy,
                defaultConsistencyLevel);

            // Create a simple stored procedure
            var scriptId = "bulkImportScript";
            var sproc    = new StoredProcedure
            {
                Id   = scriptId,
                Body = @"
function bulkImport(docs) {
    var collection = getContext().getCollection();
    var collectionLink = collection.getSelfLink();

    // The count of imported docs, also used as current doc index.
    var count = 0;

    // Validate input.
    if (!docs) throw new Error(""The array is undefined or null."");

    var docsLength = docs.length;
            if (docsLength == 0)
            {
                getContext().getResponse().setBody(0);
            }

            // Call the CRUD API to create a document.
            tryCreate(docs[count], callback);

            // Note that there are 2 exit conditions:
            // 1) The createDocument request was not accepted. 
            //    In this case the callback will not be called, we just call setBody and we are done.
            // 2) The callback was called docs.length times.
            //    In this case all documents were created and we don't need to call tryCreate anymore. Just call setBody and we are done.
            function tryCreate(doc, callback) {
            // If you are sure that every document will contain its own (unique) id field then
            // disable the option to auto generate ids.
            // by leaving this on, the entire document is parsed to check if there is an id field or not
            // by disabling this, parsing of the document is skipped because you're telling DocumentDB 
            // that you are providing your own ids.
            // depending on the size of your documents making this change can have a significant 
            // improvement on document creation. 
            var options = {
            disableAutomaticIdGeneration: true
        };

        var isAccepted = collection.createDocument(collectionLink, doc, options, callback);

        // If the request was accepted, callback will be called.
        // Otherwise report current count back to the client, 
        // which will call the script again with remaining set of docs.
        // This condition will happen when this stored procedure has been running too long
        // and is about to get cancelled by the server. This will allow the calling client
        // to resume this batch from the point we got to before isAccepted was set to false
        if (!isAccepted) getContext().getResponse().setBody(count);
    }

    // This is called when collection.createDocument is done and the document has been persisted.
    function callback(err, doc, options)
    {
        if (err) throw err;

        // One more document has been inserted, increment the count.
        count++;

        if (count >= docsLength)
        {
            // If we have created all documents, we are done. Just set the response.
            getContext().getResponse().setBody(count);
        }
        else
        {
            // Create next document.
            tryCreate(docs[count], callback);
        }
    }
}
"
            };

            sproc = client.CreateStoredProcedureAsync(collectionUri, sproc).Result.Resource;

            var doc = new MyObject(1);

            var args = new dynamic[] { new dynamic[] { doc } };

            RequestOptions requestOptions = ApplyRequestOptions(new RequestOptions {
                PartitionKey = new PartitionKey("value")
            }, serializerSettings);

            StoredProcedureResponse <int> scriptResult = client.ExecuteStoredProcedureAsync <int>(
                sproc.SelfLink,
                requestOptions,
                args).Result;

            var docUri  = UriFactory.CreateDocumentUri(databaseName, collectionName, doc.id);
            var readDoc = client.ReadDocumentAsync <MyObject>(docUri, requestOptions).Result.Document;

            Assert.IsNotNull(readDoc.SerializedObject);
            Assert.AreEqual(doc.SerializedObject.Name, readDoc.SerializedObject.Name);
        }
Esempio n. 24
0
 private Uri CreateDocumentUri(string documentId)
 {
     return(UriFactory.CreateDocumentUri(_options.Value.DatabaseName, _options.Value.CollectionName, documentId));
 }
 public async Task <Document> UpsertItemAsync <T>(string id, T item) where T : class
 {
     return(await Client.UpsertDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), item));
 }
Esempio n. 26
0
 public async Task <Document> UpdateItemAsync(T item)
 {
     return(await _client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, item.Id.ToString()), item));
 }
        /// <summary>
        /// Subscribes to a subscribtion.
        /// </summary>
        /// <param name="context">A <see cref="IDialogContext"/>.</param>
        /// <param name="result">A <see cref="IMessageActivity"/>.</param>
        /// <returns>A <see cref="Task"/>.</returns>
        public async Task SubscribeAsync(IDialogContext context, IAwaitable <IMessageActivity> result)
        {
            context.ThrowIfNull(nameof(context));
            result.ThrowIfNull(nameof(result));

            var activity = await result;
            var text     = (activity.RemoveRecipientMention() ?? string.Empty).ToLowerInvariant();
            var reply    = context.MakeMessage();

            var matchSubscribe   = Regex.Match(text, CommandMatchSubscribe);
            var matchUnsubscribe = Regex.Match(text, CommandMatchUnsubscribe);

            if (matchSubscribe.Success || matchUnsubscribe.Success)
            {
                var typing = context.MakeMessage();
                typing.Type = ActivityTypes.Typing;
                await context.PostAsync(typing);
            }

            if (matchSubscribe.Success)
            {
                var subscriptionType = (SubscriptionType)Enum.Parse(typeof(SubscriptionType), matchSubscribe.Groups[1].Value, true);
                var querySpec        = new SqlQuerySpec
                {
                    QueryText  = "SELECT * FROM subscriptions s WHERE s.channelId = @channelId AND s.userId = @userId AND s.subscriptionType = @subscriptionType",
                    Parameters = new SqlParameterCollection
                    {
                        new SqlParameter("@channelId", activity.ChannelId),
                        new SqlParameter("@userId", activity.From.Id),
                        new SqlParameter("@subscriptionType", subscriptionType)
                    }
                };

                var subscription = this.documentClient
                                   .CreateDocumentQuery <Subscription>(UriFactory.CreateDocumentCollectionUri("botdb", "subscriptioncollection"), querySpec)
                                   .ToList()
                                   .FirstOrDefault();

                if (subscription != null)
                {
                    context.Done(reply);
                    return;
                }

                var teamProjects = await this.VstsService.GetProjects(this.Account, this.Profile.Token);

                var teamProject = teamProjects.FirstOrDefault(tp => tp.Name.Equals(this.TeamProject, StringComparison.OrdinalIgnoreCase));

                if (teamProject == null)
                {
                    context.Done(reply);
                    return;
                }

                subscription = new Subscription
                {
                    BotId            = activity.Recipient.Id,
                    BotName          = activity.Recipient.Name,
                    ChannelId        = activity.ChannelId,
                    IsActive         = true,
                    ProfileId        = this.Profile.Id,
                    RecipientId      = activity.From.Id,
                    RecipientName    = activity.From.Name,
                    ServiceUri       = new Uri(activity.ServiceUrl),
                    SubscriptionType = subscriptionType,
                    TenantId         = activity.ChannelId.Equals(ChannelIds.Msteams) ? activity.GetTenantId() : string.Empty,
                    UserId           = activity.From.Id
                };

                var strategy = this.strategies.First(s => s.CanGetSubscription(subscriptionType));
                var s2       = strategy.GetSubscription(subscription.Id, teamProject);

                var r = await this.VstsService.CreateSubscription(this.Account, s2, this.Profile.Token);

                subscription.IdentityId     = r.CreatedBy.Id;
                subscription.SubscriptionId = r.Id;

                await this.documentClient.UpsertDocumentAsync(
                    UriFactory.CreateDocumentCollectionUri("botdb", "subscriptioncollection"), subscription);

                reply.Text = Labels.Subscribed;

                await context.PostAsync(reply);

                context.Done(reply);
            }
            else if (matchUnsubscribe.Success)
            {
                var subscriptionType = (SubscriptionType)Enum.Parse(typeof(SubscriptionType), matchUnsubscribe.Groups[1].Value, true);
                var querySpec        = new SqlQuerySpec
                {
                    QueryText  = "SELECT * FROM subscriptions s WHERE s.channelId = @channelId AND s.userId = @userId AND s.subscriptionType = @subscriptionType",
                    Parameters = new SqlParameterCollection
                    {
                        new SqlParameter("@channelId", activity.ChannelId),
                        new SqlParameter("@userId", activity.From.Id),
                        new SqlParameter("@subscriptionType", subscriptionType)
                    }
                };

                var subscription = this.documentClient
                                   .CreateDocumentQuery <Subscription>(UriFactory.CreateDocumentCollectionUri("botdb", "subscriptioncollection"), querySpec)
                                   .ToList()
                                   .FirstOrDefault();

                if (subscription != null)
                {
                    await this.documentClient.DeleteDocumentAsync(UriFactory.CreateDocumentUri("botdb", "subscriptioncollection", subscription.Id.ToString()));

                    await this.VstsService.DeleteSubscription(this.Account, subscription.SubscriptionId, this.Profile.Token);

                    reply.Text = Labels.Unsubscribed;
                    await context.PostAsync(reply);
                }

                context.Done(reply);
            }
            else
            {
                context.Fail(new UnknownCommandException(activity.Text));
            }
        }
Esempio n. 28
0
 public async Task DeleteItemAsync(Guid id)
 {
     await _client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id.ToString()));
 }
 public async Task DeleteItemAsync(string id)
 {
     await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id));
 }
 public async Task UpdateAsync(Entity document)
 {
     var documentUri = UriFactory.CreateDocumentUri(_dataStorageOptions.DatabaseId, _collectionId, document.Id);
     var response    = await _client.ReplaceDocumentAsync(documentUri, document).ConfigureAwait(false);
 }