Beispiel #1
0
        static async Task CreateAppAsync()
        {
            for (int i = 1; i < 21; i++)
            {
                var app = new StoreApp
                {
                    Id          = Guid.NewGuid().ToString(),
                    Name        = $"App {i}",
                    Description = "Description of App {i}",
                    Icon        = $"app{i}.png",
                    CoverPhoto  = $"cover{i}.jpg",
                    Category    = "Business",
                    Developer   = new Developer
                    {
                        Name = $"Developer {i}",
                        Icon = $"developer{i}.png",
                        Url  = "some url"
                    },
                    Version    = $"{i}.0.1",
                    PackageUrl = "package.exe",
                };

                Console.Write($"{i} ");
                var result = await _container.CreateItemAsync(app);

                Console.WriteLine(result.StatusCode);
            }
        }
        public async Task <IActionResult> Add(LocationModel model, IFormCollection collection)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    //Add a new item to CosmosDB
                    model.Id = Guid.NewGuid().ToString();
                    await docContainer.CreateItemAsync(model, new PartitionKey(model.Country));

                    return(RedirectToAction("Index"));
                }
                else
                {
                    return(View());
                }
            }
            catch (CosmosException ex)
            {
                Console.WriteLine(ex.ToString());
                return(View());
            }
            catch (Exception ex)
            {
                return(View());
            }
        }
Beispiel #3
0
        public async Task <string> AddItemAsync(T item)
        {
            item.Id = GenerateId(item);
            await _container.CreateItemAsync <T>(item, new PartitionKey(item.Id.ToString()));

            return(item.Id);
        }
        /// <summary>
        ///     Audit a item by adding it to the audit container
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private async Task Audit(T item)
        {
            Audit auditItem = new Core.Entities.Audit(item.GetType().Name,
                                                      item.Id,
                                                      Newtonsoft.Json.JsonConvert.SerializeObject(item));

            auditItem.Id = GenerateAuditId(auditItem);
            await _auditContainer.CreateItemAsync <Audit>(auditItem, ResolveAuditPartitionKey(auditItem.Id));
        }
Beispiel #5
0
        public static async Task <DateTime> UpdateLastRun(ILogger log)
        {
            // Set variable to keep lastRun time
            DateTime lastRun;

            // Bootstrap object to update DB with new date
            BotLastRun freshDeskBotLastRun = new BotLastRun()
            {
                Id = "0"
            };

            try
            {
                //Connect to DB
                await EnsureCosmosDBAsync(log);

                // Create LastRun container in DB if not existing
                lastRunContainer = await database.CreateContainerIfNotExistsAsync("LastRun", "/id");

                // Read the item to see if it exists.
                ItemResponse <BotLastRun> freshDeskBotLastRunResponse;
                freshDeskBotLastRunResponse = await lastRunContainer.ReadItemAsync <BotLastRun>(freshDeskBotLastRun.Id, new PartitionKey(freshDeskBotLastRun.Id));

                log.LogInformation("Last run time (GMT) was: {0}\n", freshDeskBotLastRunResponse.Resource.LastRun);

                // Keep the last run time as return parameter of the function
                lastRun = freshDeskBotLastRunResponse.Resource.LastRun;

                // Update the lastrun time in DB
                freshDeskBotLastRun.LastRun = DateTime.Now.ToUniversalTime();
                freshDeskBotLastRunResponse = await lastRunContainer.ReplaceItemAsync <BotLastRun>(freshDeskBotLastRun, freshDeskBotLastRun.Id, new PartitionKey(freshDeskBotLastRun.Id));

                return(lastRun);
            }
            catch (CosmosException ex) when(ex.StatusCode == HttpStatusCode.NotFound)
            {
                try
                {
                    lastRun = DateTime.Now;

                    // Set current time as initial value in DB
                    log.LogInformation("Setting initial last run time to: {0}", freshDeskBotLastRun.LastRun);
                    freshDeskBotLastRun.LastRun = DateTime.Now.ToUniversalTime();
                    ItemResponse <BotLastRun> botConversationStateResponse = await lastRunContainer.CreateItemAsync(freshDeskBotLastRun, new PartitionKey(freshDeskBotLastRun.Id));

                    return(lastRun);
                }
                catch (Exception ex2)
                {
                    log.LogError("Exception occurred in ReplaceFreshDeskBotStateAsync: {1}", ex2);
                    throw;
                }
            }
        }
Beispiel #6
0
        public async Task <string> AddItemAsync(T item)
        {
            item.Id           = GenerateId(item);
            item.EntityStatus = EntityStatus.Active;
            DateTime now = DateTime.UtcNow;

            item.DateCreatedUTC  = now;
            item.DateModifiedUTC = now;
            // TODO (SS): update CreatedBy and ModifiedBy when authentication is in place
            await _container.CreateItemAsync <T>(item, ResolvePartitionKey(item.Id));

            return(item.Id);
        }
        public async Task <IActionResult> Add(LocationModel model)
        {
            if (ModelState.IsValid)
            {
                //Add a new item to CosmosDB
                model.Id = Guid.NewGuid().ToString();
                await docContainer.CreateItemAsync(model, new PartitionKey(model.Country));

                return(RedirectToAction("index"));
            }
            else
            {
                return(View());
            }
        }
Beispiel #8
0
        //Method for Bulk insert records using createAsync method
        public async void BulkInsertCreateAsyncMethod(List <PricePaidData> lstPricedata)
        {
            //Define the conectivity option to cosmos client
            CosmosClientOptions options = new CosmosClientOptions()
            {
                AllowBulkExecution                    = true,
                ConnectionMode                        = ConnectionMode.Direct,
                MaxRequestsPerTcpConnection           = -1,
                MaxTcpConnectionsPerEndpoint          = -1,
                ConsistencyLevel                      = ConsistencyLevel.Eventual,
                MaxRetryAttemptsOnRateLimitedRequests = 999,
                MaxRetryWaitTimeOnRateLimitedRequests = TimeSpan.FromHours(1),
            };

            #region CosmosDB Connection settings

            CosmosClient client   = new CosmosClient(EndpointUrl, AuthorizationKey, options);
            Database     database = await client.CreateDatabaseIfNotExistsAsync(DatabaseName);

            //Container container = await database.CreateContainerIfNotExistsAsync(ContainerName, "/Postcode");
            Container container = await database.DefineContainer(ContainerName, "/Postcode").WithIndexingPolicy()
                                  .WithIndexingMode(IndexingMode.Consistent).WithIncludedPaths().Attach()
                                  .WithExcludedPaths().Path("/*").Attach().Attach()
                                  .CreateIfNotExistsAsync(5000);


            //database.ReplaceThroughputAsync()

            //ThroughputResponse throughput = await container.ReplaceThroughputAsync(20000);
            #endregion
            int         cnt   = 0;
            List <Task> tasks = new List <Task>();



            foreach (var item in lstPricedata)
            {
                cnt++; // only used for debugging to see current record index being processed
                tasks.Add(container.CreateItemAsync <PricePaidData>(item, new PartitionKey(item.Postcode)));
            }

            await Task.WhenAll(tasks);

            //throughput = await container.ReplaceThroughputAsync(400);
        }
Beispiel #9
0
        public static async Task UpdateEventTable(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "add-event/{device_id}/{country}/{city}/{email}/{latitude}/{longitude}/{time_str}/{is_false_alarm_str}/{event_details}/{num_of_injured}")] HttpRequestMessage request,
            [SignalR(HubName = "CounterHub")] IAsyncCollector <SignalRMessage> signalRMessages,
            string device_id, string country, string city, string email, string latitude, string longitude, string time_str,
            string is_false_alarm_str, string event_details, string num_of_injured,
            ILogger log)
        {
            cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
            database     = cosmosClient.GetDatabase(databaseId);
            container    = database.GetContainer(containerId);
            int event_id = await GetMaxId(container) + 1;

            Events newEvent = new Events
            {
                id             = event_id.ToString(),
                event_id       = event_id,
                device_id      = device_id,
                email          = email,
                country        = country,
                city           = city,
                latitude       = latitude,
                longitude      = longitude,
                is_false_alarm = is_false_alarm_str,
                event_details  = event_details,
                num_of_injured = num_of_injured,
                time           = time_str
            };

            log.LogInformation(newEvent.id.ToString());
            try
            {
                // Read the item to see if it exists.
                ItemResponse <Events> newEventResponse = await container.CreateItemAsync <Events>(newEvent, new PartitionKey(newEvent.email));

                log.LogInformation("Item with id: {0} and email {1} was added\n", newEventResponse.Resource.id, newEventResponse.Resource.email);
            }
            catch (CosmosException ex)
            {
                log.LogInformation("Error adding item to events table: {0}\n", ex);
            }
        }
Beispiel #10
0
 public async Task AddItemAsync(T item)
 {
     item.Id = GenerateId(item);
     await _container.CreateItemAsync <T>(item, ResolvePartitionKey(item.Id));
 }
 static async Task InsertNewItem(Film f)
 {
     var response = await container.CreateItemAsync <Film>(f, new PartitionKey(f.Country));
 }
Beispiel #12
0
        public static async Task AddItemsToContainerAsync(BotConversationState botConversationState, ILogger log)
        {
            try
            {
                //Connect to DB
                await EnsureCosmosDBAsync(log);

                // Read the item to see if it exists.
                ItemResponse <BotConversationState> botConversationStateResponse = await botStateContainer.ReadItemAsync <BotConversationState>(botConversationState.FreshDeskId, new PartitionKey(botConversationState.FreshDeskId));

                log.LogInformation("Conversation in database corresponding to FreshDeskId: {0} already exists\n", botConversationStateResponse.Resource.BotConversationId);
            }
            catch (CosmosException ex) when(ex.StatusCode == HttpStatusCode.NotFound)
            {
                try
                {
                    // Create an item in the container
                    ItemResponse <BotConversationState> botConversationStateResponse = await botStateContainer.CreateItemAsync(botConversationState, new PartitionKey(botConversationState.FreshDeskId));

                    log.LogInformation("Created item in database with ConversationId: {0} \n", botConversationStateResponse.Resource.BotConversationId);
                }
                catch (Exception ex2)
                {
                    log.LogError("Exception occurred in AddItemsToContainerAsync: {1}", ex2);
                    throw;
                }
            }
        }
 public async Task <T> AddItemAsync(T item)
 {
     return(await _container.CreateItemAsync <T>(item, ResolvePartitionKey(item.id)));
 }