Giter VIP home page Giter VIP logo

cosmosdb_with_csharp-sample2's Introduction

CosmosDB_with_Csharp-sample2

Source code

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Azure.Cosmos;
using System.Collections.Concurrent;
using System.ComponentModel;

namespace CosmosDBApp
{
    class Program
    {
        static async Task Main(string[] args)
        {
            IConfiguration configuration = new ConfigurationBuilder()
                        .SetBasePath(Directory.GetCurrentDirectory())
                        .AddJsonFile("appsettings.json")
                        .Build();

            CosmosSettings cosmosSettings = configuration.GetSection("CosmosSettings").Get<CosmosSettings>();

            using CosmosClient client = new(
                accountEndpoint: cosmosSettings.Endpoint,
                authKeyOrResourceToken: cosmosSettings.Key
            );

            Database database = await client.CreateDatabaseIfNotExistsAsync(cosmosSettings.DatabaseId);
            Console.WriteLine($"New database:\t{database.Id}");

            Microsoft.Azure.Cosmos.Container container = await database.CreateContainerIfNotExistsAsync(
                id: cosmosSettings.ContainerId,
                partitionKeyPath: "/categoryId",
                throughput: 400
            );
            Console.WriteLine($"New container:\t{container.Id}");

            Product newItem = new Product
            {
                id = "70b63682-b93a-4c77-aad2-65501347265f",
                categoryId = "61dba35b-4f02-45c5-b648-c6badc0cbd79",
                categoryName = "gear-surf-surfboards",
                name = "Yamba Surfboard",
                quantity = 12,
                sale = false
            };

            Product createdItem = await container.CreateItemAsync(newItem, new PartitionKey(newItem.categoryId));
            Console.WriteLine($"Created item:\t{createdItem.id}\t[{createdItem.categoryName}]");

            Product readItem = await container.ReadItemAsync<Product>(newItem.id, new PartitionKey(newItem.categoryId));

            var query = new QueryDefinition("SELECT * FROM products p WHERE p.categoryId = @categoryId")
                .WithParameter("@categoryId", newItem.categoryId);

            using FeedIterator<Product> feed = container.GetItemQueryIterator<Product>(queryDefinition: query);

            while (feed.HasMoreResults)
            {
                FeedResponse<Product> response = await feed.ReadNextAsync();
                foreach (Product item in response)
                {
                    Console.WriteLine($"Found item:\t{item.name}");
                }
            }
        }
    }

    public class CosmosSettings
    {
        public string Endpoint { get; set; }
        public string Key { get; set; }
        public string DatabaseId { get; set; }
        public string ContainerId { get; set; }
    }

    public class Product
    {
        public string id { get; set; }
        public string categoryId { get; set; }
        public string categoryName { get; set; }
        public string name { get; set; }
        public int quantity { get; set; }
        public bool sale { get; set; }
    }
}

appsettings.json

{
  "CosmosSettings": {
    "Endpoint": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "Key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "DatabaseId": "cosmicworks",
    "ContainerId": "products"
  }
}

Azure CosmosDB "EndPoint" and "Key"

The above "Endpoint" and "Key" corresponds with the "URI" and "PRIMARY KEY" image

cosmosdb_with_csharp-sample2's People

Contributors

luiscoco avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.