Esempio n. 1
0
 public LocationsController(IMemoryCache cache, CosmosClient client)
 {
     countryCache = cache;
     docClient    = client;
     docContainer = docClient.GetContainer(
         "m3globocdb", "globolocations");
 }
Esempio n. 2
0
        public static async Task <List <CityCount> > AggCityCount(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "agg-city-count")] HttpRequestMessage request,
            ILogger log)
        {
            cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
            database     = cosmosClient.GetDatabase(databaseId);
            container    = database.GetContainer(containerId);
            List <CityCount> eventsCountArray = new List <CityCount>()
            {
            };
            var sqlQueryText = "SELECT c.city as name, count(c.event_id) as y from c " +
                               "GROUP BY c.city";


            Console.WriteLine("Running query: {0}\n", sqlQueryText);

            QueryDefinition          queryDefinition        = new QueryDefinition(sqlQueryText);
            FeedIterator <CityCount> queryResultSetIterator = container.GetItemQueryIterator <CityCount>(queryDefinition);

            while (queryResultSetIterator.HasMoreResults)
            {
                FeedResponse <CityCount> currentResultSet = await queryResultSetIterator.ReadNextAsync();

                foreach (CityCount i in currentResultSet)
                {
                    Console.WriteLine("\tRead {0}\n", i);
                    eventsCountArray.Add(i);
                }
            }
            return(eventsCountArray);
        }
Esempio n. 3
0
        public static async Task <List <NumOfInjuredCount> > AggInjuredCount(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "agg-injured--count")] HttpRequestMessage request,
            [SignalR(HubName = "CounterHub")] IAsyncCollector <SignalRMessage> signalRMessages,
            ILogger log)
        {
            cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
            database     = cosmosClient.GetDatabase(databaseId);
            container    = database.GetContainer(containerId);
            List <NumOfInjuredCount> eventsCountArray = new List <NumOfInjuredCount>()
            {
            };
            var sqlQueryText = "SELECT c.num_of_injured as label, count(c.event_id) as y from c " +
                               "WHERE c.is_false_alarm = 'False' " +
                               "GROUP BY c.num_of_injured";

            Console.WriteLine("Running query: {0}\n", sqlQueryText);

            QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText);
            FeedIterator <NumOfInjuredCount> queryResultSetIterator = container.GetItemQueryIterator <NumOfInjuredCount>(queryDefinition);

            while (queryResultSetIterator.HasMoreResults)
            {
                FeedResponse <NumOfInjuredCount> currentResultSet = await queryResultSetIterator.ReadNextAsync();

                foreach (NumOfInjuredCount i in currentResultSet)
                {
                    Console.WriteLine("\tRead {0}\n", i);
                    eventsCountArray.Add(i);
                }
            }
            return(eventsCountArray);
        }
Esempio n. 4
0
        public static async Task <List <EventdayCount> > AggEventsEachDay(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "agg-event-day")] HttpRequestMessage request,
            [SignalR(HubName = "CounterHub")] IAsyncCollector <SignalRMessage> signalRMessages,
            ILogger log)
        {
            cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
            database     = cosmosClient.GetDatabase(databaseId);
            container    = database.GetContainer(containerId);
            List <EventdayCount> eventsCountArray = new List <EventdayCount>()
            {
            };
            var sqlQueryText = "SELECT table.time as x, count(table.event_id) as y from" +
                               " (SELECT c.event_id as event_id, SUBSTRING(c.time, 0, 10) as time  FROM c) as table" +
                               " GROUP BY table.time";

            Console.WriteLine("Running query: {0}\n", sqlQueryText);

            QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText);
            FeedIterator <EventdayCount> queryResultSetIterator = container.GetItemQueryIterator <EventdayCount>(queryDefinition);

            while (queryResultSetIterator.HasMoreResults)
            {
                FeedResponse <EventdayCount> currentResultSet = await queryResultSetIterator.ReadNextAsync();

                foreach (EventdayCount i in currentResultSet)
                {
                    Console.WriteLine("\tRead {0}\n", i);
                    eventsCountArray.Add(i);
                }
            }
            eventsCountArray.Sort((x, y) => DateTime.Compare(x.x, y.x));
            return(eventsCountArray);
        }
Esempio n. 5
0
        public static async Task <List <Events> > GetHistoryEvents(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "get_history_events")] HttpRequestMessage request,
            ILogger log)
        {
            cosmosClient = new CosmosClient(EndpointUri, PrimaryKey);
            database     = cosmosClient.GetDatabase(databaseId);
            container    = database.GetContainer(containerId);
            List <Events> eventsCountArray = new List <Events>()
            {
            };
            var sqlQueryText = "SELECT * from c";

            Console.WriteLine("Running query: {0}\n", sqlQueryText);

            QueryDefinition       queryDefinition        = new QueryDefinition(sqlQueryText);
            FeedIterator <Events> queryResultSetIterator = container.GetItemQueryIterator <Events>(queryDefinition);

            while (queryResultSetIterator.HasMoreResults)
            {
                FeedResponse <Events> currentResultSet = await queryResultSetIterator.ReadNextAsync();

                foreach (Events i in currentResultSet)
                {
                    Console.WriteLine("\tRead {0}\n", i);
                    eventsCountArray.Add(i);
                }
            }
            return(eventsCountArray);
        }
Esempio n. 6
0
 public CosmosDbService(
     CosmosClient dbClient,
     string databaseName,
     string containerName)
 {
     this._container = dbClient.GetContainer(databaseName, containerName);
 }
 public LocationsController(IMemoryCache cache, CosmosClient client)
 {
     countryCache = cache;
     docClient    = client;
     //In Azure Cosmos DB, we create a database and inside that database, we have a container and inside that container, we will have items.
     //A database is analogous to a namespace. It is the unit of management for a set of containers.
     docContainer = docClient.GetContainer("sample-database", "sample-container");
 }
Esempio n. 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CosmosUserRepository{T}"/> class.
        /// </summary>
        /// <param name="cosmosConfiguration">Configuration to create connection with an Azure Cosmos DB Database</param>
        /// <param name="loggerFactory">Logger factory to create a logger</param>
        public CosmosUserRepository(CosmosConfiguration cosmosConfiguration, ILoggerFactory loggerFactory)
            : base(cosmosConfiguration, loggerFactory)
        {
            this.Logger.LogTrace("Beginning construction of Cosmos User Repository");

            this.container = this.CosmosClient.GetContainer(this.DatabaseId, UserBase.ContainerId);

            this.Logger.LogTrace("Construction of Cosmos User Repository complete");
        }
Esempio n. 9
0
 public MasterRepository(TelemetryLogger logger, IRepositoryClient repositoryClient, IRepositoryCosmosClient repositoryCosmosClient)
 {
     client        = repositoryClient.Client;
     databaseId    = repositoryClient.DatabaseId;
     collectionId  = repositoryClient.CollectionId;
     collectionUri = repositoryClient.CollectionUri;
     //documentCollection = repositoryClient.DocumentCollection;
     container   = repositoryCosmosClient.Container;
     this.logger = logger;
 }
Esempio n. 10
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;
                }
            }
        }
Esempio n. 11
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);
        }
Esempio n. 12
0
        static async Task Main(string[] args)
        {
            _database  = _client.GetDatabase("AppStore");
            _container = _database.GetContainer("Apps");

            //Console.WriteLine("Adding Item....");
            //Console.WriteLine("Updating Item....");
            //Console.WriteLine("Deleting Item....");
            Console.WriteLine("Getting Items....");

            await GetAppsAsync();

            //await CreateAppAsync();
            //await UpdateAppAsync();
            //await DeleteAppAsync();

            Console.ReadKey();
        }
Esempio n. 13
0
        private static async Task EnsureCosmosDBAsync(ILogger log)
        {
            try
            {
                //Create a new instance of the Cosmos Client
                cosmosClient = new CosmosClient(cosmosDBEndpointUri, cosmosDBPrimaryKey);

                //create database and container if not existing
                database = await cosmosClient.CreateDatabaseIfNotExistsAsync(cosmosDBDatabaseId);

                botStateContainer = await database.CreateContainerIfNotExistsAsync(cosmosDBContainerId, "/id");
            }
            catch (Exception ex)
            {
                log.LogError("Exception occurred in EnsureCosmosDBAsync: {1}", ex);
                throw;
            }
        }
Esempio n. 14
0
        public TenantBaseManager(string containerName, IHttpContextAccessor httpContextAccessor, IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
        {
            _moniker = httpContextAccessor.HttpContext.Request.RouteValues["moniker"] != null ? httpContextAccessor.HttpContext.Request.RouteValues["moniker"].ToString() : string.Empty;
            //_tenant = customerService.GetItemAsync(_moniker);

            if (_tenant == null)
            {
                return;                   //  No tenant, no entry!
            }
            SetConnectionParameters(configuration, webHostEnvironment);

            if (!string.IsNullOrEmpty(_uri) && !string.IsNullOrEmpty(_primaryKey))
            {
                CosmosClientBuilder clientBuilder = new CosmosClientBuilder(_uri, _primaryKey);
                _dbClient  = clientBuilder.WithConnectionModeDirect().Build();
                _container = _dbClient.GetContainer(_databaseName, containerName);
            }
        }
        private async Task InitClientsAsync()
        {
            CosmosClientPool.CreateClient(this.cosmosDBSettings.Producer);
            CosmosClientPool.CreateClient(this.cosmosDBSettings.Lease);

            //await CosmosExtension.SetupCosmosDBEntitiesAsync(this.cosmosDBSettings.Producer);

            await CosmosExtension.SetupCosmosDBEntitiesAsync(this.cosmosDBSettings.Lease);

            Microsoft.Azure.Cosmos.Container leaseContainer  = CosmosClientPool.GetCosmosClient(this.cosmosDBSettings.Lease).GetContainer(this.cosmosDBSettings.Lease.Database, this.cosmosDBSettings.Lease.Container);
            Microsoft.Azure.Cosmos.Container sourceContainer = CosmosClientPool.GetCosmosClient(this.cosmosDBSettings.Producer).GetContainer(this.cosmosDBSettings.Producer.Database, this.cosmosDBSettings.Producer.Container);
            this.changeFeedProcessor = sourceContainer
                                       .GetChangeFeedProcessorBuilder <EventDataModel>("changeFeedBeginning", this.changesHandler)
                                       .WithInstanceName("EventprocessingConsole")
                                       .WithLeaseContainer(leaseContainer)
                                       .WithStartTime(DateTime.MinValue.ToUniversalTime())
                                       .Build();
            await this.changeFeedProcessor.StartAsync();
        }
Esempio n. 16
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);
            }
        }
Esempio n. 17
0
 public CosmosDbRepository(ICosmosDbContainerFactory cosmosDbContainerFactory)
 {
     this._cosmosDbContainerFactory = cosmosDbContainerFactory ?? throw new ArgumentNullException(nameof(ICosmosDbContainerFactory));
     this._container = this._cosmosDbContainerFactory.GetContainer(ContainerName)._container;
 }
Esempio n. 18
0
 static async Task CreateContainerAsync()
 {
     container = await database.CreateContainerIfNotExistsAsync(containerId, "/Country");
 }
 public CosmosDbService(string connectionString)
 {
     _client    = new CosmosClient(connectionString);
     _container = _client.GetContainer("coreDB", "MyItem");
 }
Esempio n. 20
0
 public PrayerGroupRepository(CosmosClientService cosmosClientService)
 {
     this._container = cosmosClientService.CosmosClient.GetContainer(cosmosClientService.DatabaseName, CONTAINER_NAME);
 }