Exemple #1
0
        public async Task <ActionResult> DeleteConfirmedAsync([Bind("Id, Category")] string id,
                                                              string category)
        {
            await CosmosService.DeleteItemAsync(id, category);

            return(this.RedirectToAction("Index"));
        }
        internal static HttpResponseMessage ConvertHttpResponseMessage(this Response response)
        {
            if (response == null)
            {
                return(CosmosService.ErrorResponse("There was no response from Azure Cosmos."));
            }

            // Would be really nice if we could simply pass the Cosmos response directly back,
            // but, alas, we must reconstruct a return response.
            var result = new HttpResponseMessage();

            // Pass Cosmos response headers back.
            foreach (var headerName in response.Headers)
            {
                result.Headers.Add(headerName.Name, headerName.Value);
            }

            // Pass Cosmos status code back.
            result.StatusCode = (HttpStatusCode)response.Status;

            if (response.ContentStream != null)
            {
                // Pass stream directly to response object, without deserializing.
                result.Content = new StreamContent(response.ContentStream);
            }

            return(result);
        }
Exemple #3
0
        public static async Task <HttpResponseMessage> GetResponseAsync(this HttpRequest request)
        {
            try
            {
                if (request == null)
                {
                    throw new ArgumentNullException(nameof(request));
                }

                int parts = request.Path.ParseRoute(
                    out string database,
                    out string container,
                    out string partitionKey,
                    out string id,
                    out int maxItemCount);

                return((request.Method.ToLowerInvariant()) switch
                {
                    "get" => await CosmosService.ReadItemStreamAsync(database, container, partitionKey, id),
                    "post" => parts == 4
                        ? await CosmosService.CreateItemStreamAsync(database, container, partitionKey, request.Body)
                        : await CosmosService.GetItemQueryStreamIterator(database, container, partitionKey, request.Body, request.Headers["Continuation-Token"], maxItemCount),
                    "put" => parts == 4
                        ? await CosmosService.UpsertItemStreamAsync(database, container, partitionKey, request.Body)
                        : await CosmosService.ReplaceItemStreamAsync(database, container, partitionKey, id, request.Body),
                    "delete" => await CosmosService.DeleteItemStreamAsync(database, container, partitionKey, id),
                    _ => CosmosService.ErrorResponse("Request method did not match one of the Cosmos API method signatures.")
                });
            }
        public async Task SendItemAsyncTest()
        {
            var post = new Post {
                PostId = 99999999
            };

            await CosmosService.AddItemToContainerAsync(post);
        }
        public async Task DeleteItemAsync()
        {
            var post = new Post {
                PostId = 99999999
            };

            var id = await CosmosService.AddItemToContainerAsync(post);

            await CosmosService.DeleteItemAsync(id, post.PostId.Value.ToString());
        }
Exemple #6
0
        public async Task <ActionResult> EditAsync([Bind("Id,Name,Description,Completed,Category")]
                                                   TodoItem item)
        {
            if (this.ModelState.IsValid)
            {
                await CosmosService.UpdateItemAsync(item);

                return(this.RedirectToAction("Index"));
            }

            return(this.View(item));
        }
Exemple #7
0
        private static async void Execute()
        {
            Console.WriteLine(string.Format("Csv File: {0}", CSV_FILE_LOCATION));

            Console.WriteLine(string.Format("Cosmos DB Collection: {0}", COSMOS_DB_COLLECTION_ID));
            Console.WriteLine(string.Format("Cosmos DB Database ID: {0}", COSMOS_DB_DATABASE_ID));

            using (var reader = new StreamReader(CSV_FILE_LOCATION))
                using (var csvReader = new CsvReader(reader))
                {
                    Console.WriteLine(string.Format("Start reading CSV file: {0}", CSV_FILE_LOCATION));

                    csvReader.Configuration.MissingFieldFound = null;
                    csvReader.Configuration.Delimiter         = ",";
                    bool result = await csvReader.ReadAsync();

                    if (result)
                    {
                        csvReader.ReadHeader();
                        List <dynamic> records = csvReader.GetRecords <dynamic>()?.ToList();

                        Console.WriteLine(string.Format("{0} item(s) found in CSV", records.Count()));
                        int countOfSegmentsPerThread = GetCountOfSegmentsPerThread(records.Count(), NUMBER_OF_THREADS);
                        Console.WriteLine(string.Format("Count of segments per Thread: {0}", countOfSegmentsPerThread));

                        int           countOfSkippedItems = 0;
                        CosmosService cosmosService       = new CosmosService(COSMOS_DB_URL, COSMOS_DB_PRIMARY_KEY, COSMOS_DB_DATABASE_ID, COSMOS_DB_COLLECTION_ID, COSMOS_DB_PRE_TRIGGER_NAME, COSMOS_DB_POST_TRIGGER_NAME);

                        List <Task> taskList = new List <Task>();

                        Watch = new Stopwatch();
                        Watch.Start();
                        StartTimer();

                        for (int i = 0; i < NUMBER_OF_THREADS; i++)
                        {
                            IEnumerable <dynamic> skippedRecords = records.Skip(countOfSkippedItems).Take(countOfSegmentsPerThread);

                            Task task = StartExecuteWebserviceRequest(records, cosmosService);
                            taskList.Add(task);
                            Console.WriteLine(string.Format("Thread No. {0} started, Thread-Id {1} has to work with {2} count of records.", (i + 1), task.Id, skippedRecords.Count().ToString("n")));

                            if (i == 0 && countOfSkippedItems == 0)
                            {
                                countOfSkippedItems = countOfSegmentsPerThread;
                            }

                            countOfSkippedItems = (countOfSkippedItems + countOfSegmentsPerThread);
                        }
                    }
                }
        }
Exemple #8
0
        private static async Task <CosmosService> InitCosmosClientAsync(IConfigurationSection configurationSection)
        {
            string databaseName  = configurationSection.GetSection("DatabaseName").Value;
            string containerName = configurationSection.GetSection("ContainerName").Value;
            string account       = configurationSection.GetSection("Account").Value;
            string key           = Environment.GetEnvironmentVariable("CosmosKey");

            CosmosClient     client        = new CosmosClient(account, key);
            CosmosService    cosmosService = new CosmosService(client, databaseName, containerName);
            DatabaseResponse database      = await client.CreateDatabaseIfNotExistsAsync(databaseName);

            await database.Database.CreateContainerIfNotExistsAsync(containerName, "/id");

            return(cosmosService);
        }
Exemple #9
0
        /// <summary>
        /// Creates a Cosmos DB database and a container with the specified partition key.
        /// This will be used to pull the FlowCal repo information
        /// </summary>
        /// <returns></returns>
        private static async Task <ICosmosService> InitializeCosmosClientInstanceAsync(IConfigurationSection configurationSection)
        {
            string         databaseName  = configurationSection.GetSection("DatabaseName").Value;
            string         containerName = configurationSection.GetSection("ContainerName").Value;
            string         account       = configurationSection.GetSection("Account").Value;
            string         key           = configurationSection.GetSection("Key").Value;
            CosmosClient   client        = new Microsoft.Azure.Cosmos.CosmosClient(account, key);
            ICosmosService cosmosService = new CosmosService(client, databaseName, containerName);

            Microsoft.Azure.Cosmos.DatabaseResponse database = await client.CreateDatabaseIfNotExistsAsync(databaseName);

            await database.Database.CreateContainerIfNotExistsAsync(containerName, "/appName");

            return(cosmosService);
        }
Exemple #10
0
        public async Task <IActionResult> Create([FromBody] TandemUser user)
        {
            try
            {
                var cosmosService = new CosmosService(Configuration);
                var userId        = await cosmosService.CreateUser(user);

                return(Ok($"User successfully created with id {userId}"));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(StatusCode(StatusCodes.Status500InternalServerError, e.GetFullMessage()));
            }
        }
Exemple #11
0
        public async Task <ActionResult> DeleteAsync(string id, string category)
        {
            if (id == null)
            {
                return(new StatusCodeResult((int)HttpStatusCode.BadRequest));
            }

            var item = await CosmosService.GetTodoItemAsync(id, category);

            if (item == null)
            {
                return(this.NotFound());
            }

            return(this.View(item));
        }
Exemple #12
0
        public async Task <ActionResult> EditAsync(string id, string category)
        {
            if (id == null)
            {
                return(new BadRequestResult());
            }

            var item = await CosmosService.GetTodoItemAsync(id, category);

            if (item == null)
            {
                return(this.NotFound());
            }

            return(this.View(item));
        }
Exemple #13
0
        public async Task <StatusPayload> Index()
        {
            var cosmosService = new CosmosService(
                _apiConfiguration.CosmosDbEndpoint,
                _apiConfiguration.CosmosDbKey,
                SessionFilterAttribute.GetSessionId(HttpContext));
            //  Ask both in parallel
            var statusTask     = cosmosService.GetStatusAsync();
            var photoCountTask = cosmosService.GetImageCountAsync();

            await Task.WhenAll(statusTask, photoCountTask);

            return(new StatusPayload
            {
                Status = statusTask.Result,
                ImageCount = photoCountTask.Result
            });
        }
Exemple #14
0
    private static async Task Main(string[] args)
    {
        var myCosmosService = new CosmosService();
        await myCosmosService.InitializeAsync(endpointUrl, accountKey);

        var newContact1 = new Contact
        {
            Id        = Guid.NewGuid().ToString(),
            FirstName = "mithun",
            LastName  = "shanbhag",
            Email     = "*****@*****.**",
            City      = "Bangalore"
        };

        var newContact2 = new Contact
        {
            Id        = Guid.NewGuid().ToString(),
            FirstName = "john",
            LastName  = "doe",
            Email     = "*****@*****.**",
            City      = "Delhi"
        };

        try
        {
            await myCosmosService.AddContactAsync(newContact1);

            await myCosmosService.AddContactAsync(newContact2);

            foreach (var contact in await myCosmosService.ListContactsAsync())
            {
            }

            var contactToModify = await myCosmosService.GetContactAsync(newContact2.Id);

            contactToModify.FirstName = "Jane";
            await myCosmosService.UpdateContactAsync(contactToModify.Id, contactToModify);
        }
        finally
        {
            //await myCosmosService.DeleteContactAsync(newContact1.Id);
            //await myCosmosService.DeleteContactAsync(newContact1.Id);
        }
    }
Exemple #15
0
        public void CosmosService_Should_Return_DocumentId()
        {
            //Arrange
            var mockedRepo = new Mock <IGenericRepository <DocumentVm> >();
            var sut        = new CosmosService(mockedRepo.Object);

            var docVm = new DocumentVm {
                DocumentId = 123
            };

            mockedRepo.Setup(x => x.GetDocumentId(It.IsAny <string>())).Returns(docVm);

            //Act
            var guid   = "abc-123";
            var result = sut.GetDocumentId(guid);

            //Assert
            Assert.Equal(123, result);
        }
Exemple #16
0
        public async Task <IActionResult> Get(string emailAddress)
        {
            try
            {
                var cosmosService = new CosmosService(Configuration);
                var tandemUser    = await cosmosService.GetUser(emailAddress);

                if (tandemUser == null)
                {
                    throw new Exception($"No User found with Email Address {emailAddress}");
                }
                var mapper     = new Mapper(Config);
                var returnUser = mapper.Map <ReturnUser>(tandemUser);
                return(Ok(returnUser));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(StatusCode(StatusCodes.Status500InternalServerError, e.GetFullMessage()));
            }
        }
Exemple #17
0
        private async Task <CosmosService> InitializeCosmosClientInstanseAsync(IConfiguration configuration)
        {
            string databaseName = Configuration["DatabaseName"];
            string account      = Configuration["Endpoint"];
            string key          = Configuration["Key"];

            CosmosClientBuilder clientBuilder = new CosmosClientBuilder(account, key);
            CosmosClient        client        = clientBuilder
                                                .WithConnectionModeDirect()
                                                .Build();
            CosmosService    eventService = new CosmosService(client, databaseName, "events");
            DatabaseResponse database     = await client.CreateDatabaseIfNotExistsAsync(databaseName);

            await database.Database.CreateContainerIfNotExistsAsync("events", "/id");

            await database.Database.CreateContainerIfNotExistsAsync("tickets", "/id");

            await database.Database.CreateContainerIfNotExistsAsync("categories", "/id");

            return(eventService);
        }
Exemple #18
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            //validaciones
            //reglas
            //persistencia


            log.LogInformation("C# HTTP trigger function processed a request.");

            //string nombre = req.Query["nombre"];
            //string rut = req.Query["rut"];
            //string celular = req.Query["celular"];
            //string correo = req.Query["correo"];

            string id = req.Query["id"];

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            //nombre = nombre ?? data?.nombre;
            //rut = rut ?? data?.rut;
            //celular = celular ?? data?.celular;
            //correo = correo ?? data?.correo;

            id = id ?? data?.id;

            /*crear cosmos sevice*/
            //var cscliente = new CosmosService<Cliente>();
            //var cli = await cscliente.InsertElement(new Cliente
            //{
            //    Nombre = nombre,
            //    Rut = rut,
            //    Celular = Int32.Parse(celular),
            //    EntityName = cscliente.EntityName
            //});
            //Console.WriteLine($"Nuevo id: {cli}");

            //var cspersona  = new CosmosService<Persona>();
            //var per = await cspersona.InsertElement(new Persona {
            //    Nombre= nombre,
            //    Rut = rut,
            //    Correo = correo,
            //    EntityName = cspersona.EntityName,
            //    Celular = celular
            //});
            //Console.WriteLine($"Nuevo id: {per}");

            var cscliente = new CosmosService <Cliente>();
            var buscar    = await cscliente.GetElementById(id, cscliente.EntityName);


            string responseMessage = string.IsNullOrEmpty(id)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : JsonConvert.SerializeObject(buscar)

            ;

            return(new OkObjectResult(responseMessage));
        }
 public void Setup()
 {
     CosmosService.SetUp();
 }
        public void SendItemAsyncTest_InvalidOperationException_Fail()
        {
            var post = new Post();

            Assert.ThrowsAsync <InvalidOperationException>(async() => { await CosmosService.AddItemToContainerAsync(post); });
        }
Exemple #21
0
        public async Task <ActionResult> DetailsAsync(string id, string category)
        {
            var item = await CosmosService.GetTodoItemAsync(id, category);

            return(this.View(item));
        }
Exemple #22
0
        public async Task <ActionResult> IndexAsync()
        {
            var items = await CosmosService.GetOpenItemsAsync();

            return(this.View(items));
        }
Exemple #23
0
 private static Task StartExecuteWebserviceRequest(IEnumerable <dynamic> records, CosmosService service)
 {
     return(Task.Run(() => {
         service.SaveItems(records);
     }));
 }
 public void SendItemAsyncTest_Fail()
 {
     Assert.ThrowsAsync <NullReferenceException>(async() => { await CosmosService.AddItemToContainerAsync(null); });
 }