Azure

Highway To AZ-204 – Growing Options That Use Cosmos DB Storage

Intro

 

This text’s intention is to elucidate the principle abilities measured on this sub-topic of the AZ-204 Certification. Cosmos DB is the principle part that may have their fundamentals defined right here alongside a sensible instance.

 

This certification may be very in depth and this text approaches solely the principle subjects, be sure you know  these parts in depth earlier than taking the examination. One other nice tip is doing examination simulators earlier than the official examination as a way to validate your information.

 

What’s the Certification AZ-204 – Growing Options for Microsoft Azure?

 

The AZ-204 – Growing Options for Microsoft Azure certification measures designing, constructing, testing, and sustaining abilities of an utility and/or service within the Microsoft Azure Cloud atmosphere. It approaches, amongst others, these parts,

  • Azure Digital Machines;
  • Docker;
  • Azure Containers;
  • Service Internet App;
  • Azure Capabilities;
  • Cosmos DB;
  • Azure Storage;
  • Azure AD;
  • Azure Key Vault;
  • Azure Managed Identities;
  • Azure Redis Cache;
  • Azure Logic App;
  • Azure Occasion Grid;
  • Azure Occasion Hub;
  • Azure Notification Hub;
  • Azure Service Bus;
  • Azure Queue Storage.

 

Goal Viewers

 

Any IT skilled keen to enhance his or her information in Microsoft Azure is inspired to take this certification, it’s an effective way to measure your abilities inside trending applied sciences. However, some teams of pros are keener to take most benefit of it,

  • Azure Builders, with not less than 1 yr of expertise with Microsoft Azure;
  • Skilled Software program Builders, in search of an Architect place in a hybrid atmosphere;
  • Software program Builders, working to maneuver purposes to the cloud atmosphere.

Abilities Measured

 

In keeping with at present’s date, the talents which might be measured within the examination are cut up as follows,

  • Develop Azure compute options (25-30%)
    • Implement Azure capabilities

  • Develop for Azure storage (10-15%)
    • Develop options that use Cosmos DB storage
    • Develop options that use blob storage
  • Implement Azure safety (15-20%)
    • Implement person authentication and authorization
    • Implement safe cloud options
  • Monitor, troubleshoot, and optimize Azure options (10-15%)
    • Combine caching and content material supply inside options
    • Instrument options to assist monitoring and logging
  • Connect with and eat Azure companies and third-party companies (25- 30%)
    • Develop an App Service Logic App
    • Implement API Administration
    • Develop event-based options
    • Develop message-based options

 

Advantages of Getting Licensed

 

The primary profit right here is having a worldwide acknowledged certification that proves that you’ve got information of this matter. Amongst intrinsic and extrinsic advantages, we’ve got,

  • Increased progress potential, as certifications are an enormous plus;
  • Reductions and offers in Microsoft merchandise and companions, like PluralSight and UpWork;
  • MCP Newsletters, with trending applied sciences;
  • Increased publicity on LinkedIn, as recruiters often seek for particular certifications;
  • Increased wage, you’ll be extra worthwhile to your organization;
  • Distinctive happiness when getting the end result and also you had been permitted, understanding that every one your efforts had been price it;

 

Major abilities Measured by this Matter

 

What’s Cosmos DB?

 

Cosmos DB is a NoSQL Database with an extremely quick response time and string assist for scalability. Azure Cosmos DB presents Cosmos DB with a completely managed service, the place you don’t want to fret about its administration as a result of Azure handles the Cosmos DB computerized administration, updates, and patches.

 

Azure Cosmos DB additionally presents serverless cost-effective capability administration and computerized scalability choices and its foremost advantages are those as follows,

  • Integrates with many Azure Providers, like Azure Capabilities, Azure Kubernetes Providers, Azure App Providers;
  • Integrates with many databases APIs, just like the native Core SQL, MongoDB, Cassandra, Gremlin;
  • Integrates with many growth SDKs, like .Web, Java, Python, Node.Js;
  • Has a schema-less service that robotically applies indexes to your information, leading to quick queries;
  • Assured uptime SLA of 99,999% availability;
  • Automated information replication, amongst Azure Areas;
  • Knowledge protected with encryption-at-rest and role-based entry;
  • Totally-managed database, with updates, upkeep and patches utilized robotically;
  • Autoscale offered as a way to attend completely different sizes of workload;

 

Cosmos DB APIs

 

Azure Cosmos DB may be very versatile, being supplied by several types of APIs as a way to assist a wider vary of purposes to be coated. All these completely different APIs are supported because of the multi-model strategy, having the ability to ship information by paperwork, key-value pairs, wide-columns, or graph-data.

 

It’s strongly really helpful to make use of the Core SQL APIs for brand new tasks, whereas it’s endorsed to make use of the precise database API for current databases. These APIs are those as follows, 

  • Core SQL API, default API for utilizing Azure Cosmos DB allows querying your information with a language very near SQL;
  • MongoDB API, used to speak with MongoDB databases and storing information as paperwork;
  • Cassandra API, used to speak with Cassandra utilizing Cassandra Question Language and storing information as a partitioned row retailer;
  • Azure Desk API, used to speak with Azure Desk Storages and permitting indexes within the partition and row keys. To question information you should utilize OData, LinQ in code and the Relaxation APIs for GET operations;
  • Gremlin API, used to offer a Graph-based information view, being queried from graph traversal language.

Partitioning Schemas in Cosmos DB

 

In Azure Cosmos DB indexes the information amongst partitions, as a way to have a greater efficiency they’re grouped by the partition keys. To know higher about partitioning schemas in Azure Cosmos DB some fundamental ideas need to be defined as follows,

  • Partition Keys are the keys used to group gadgets. Works like major keys;
  • Logical Partitions consists of a set of things sharing the identical partition key worth;
  • Bodily Partitions consists of a set of logical partitions. Might have from 1 to any logical partitions and are managed by Azure Cosmos DB;
  • Reproduction-Units consists of a bunch of bodily partitions which might be materialized as a self-managed and dynamically load-balanced group of replicas unfold throughout a number of fault domains.

The ideas defined above may be higher visualized within the picture under,

 

 

Consistency ranges in Cosmos DB

 

Azure Cosmos DB presents 5 varieties of consistency ranges as a way to keep your information availability and querying efficiency relying in your wants, these consistency ranges are those as follows,

 

Sturdy Consistency

  • Reads operation ensures the return of the newest information;
  • Reads operation prices as a lot because the Bounded Staleness and greater than session and eventual consistencies;
  • Write operations are solely accessible to be learn after the information being replicated by nearly all of its replicas;

Bounded Staleness

  • Reads operations are lagged behind writes operation, by time or variations;
  • Reads operation prices as a lot because the Sturdy Consistency and greater than session and eventual consistencies;
  • Has the strongest consistency than a session consistency, consistent-prefix, or eventual consistency; 
  • Advisable for globally distributed purposes, with excessive availability and low latency;

Session

  • Reads operation assure consistency of written information in the identical session;
  • Consistency is scoped to a person session, whereas different customers might face soiled information if it has simply be written by one other session;
  • Default consistency stage used to newly created databases;
  • Reads operation prices are smaller than Bounded Staleness and Sturdy Consistency however larger than Eventual Consistency;

Constant Prefix

  • Learn operation ensures the return of the newest information replicated among the many replicas, nevertheless it doesn’t assure to have the newest information;
  • Soiled information occurs when one duplicate change the information state however this information has not been replicated but;
  • Has a stronger consistency stage than the Eventual Consistency however lower than any others.

Eventual

  • Learn operation doesn’t assure any consistency stage;
  • Weakest consistency stage;
  • Lowest latency and finest efficiency among the many consistency ranges;
  • Reads operation price lower than another consistency ranges;

Azure Cosmos Containers are helpful for Azure Cosmos DB scalability each for storage scalability and throughput scalability. However, Azure Cosmos Containers are additionally nice once you want a unique set of configurations amongst your Azure Cosmos DBs as a result of it presents the potential to configure every container individually. 

 

Azure Cosmos Container has some container-specific properties, and people properties, which may be system-generated or user-configurable, differ based on the used API.

 

These properties listing ranges from distinctive identifiers for containers to configurations of the purging insurance policies. You could discover all the properties listing right here.

 

On the creation second it’s possible you’ll configure your throughput technique between these two modes,

  1. Devoted mode, whereas the provisioned throughput configured on this container is solely for this container and is backed by SLAs;
  2. Shared mode, whereas the provisioned throughput configured on this container is shared amongst all containers with the shared mode.

Cosmos DB Containers can be found, at the moment date, for all Cosmos DB APIs, besides Gremlin API and Desk API.

 

Scaling Cosmos DB

 

Azure Cosmos DB presents guide and computerized scaling, with none interruption in your companies nor impression on Azure Cosmos DB SLA.

 

With computerized scaling, Azure Cosmos DB robotically adjusts, up or down, your throughput capability based on its utilization with no need to create any logic nor code.

 

You solely must configure your most throughput capability and Azure will alter your Azure Cosmos DB throughput from 10% of the utmost capability to 100% of the utmost capability.

 

With guide scaling, you’ll be able to change completely your throughput capability. 

 

Needless to say it’s important to have chosen your partition keys correctly earlier than scaling your Azure Cosmos DB. In any other case, your requests should not going to be balanced as your are going to expertise a sizzling partition, which elevates the prices and reduces the efficiency.

 

There are some necessary subjects that it’s essential to configure when setting autoscale, as follows,

  • Time to Dwell, defines the TTL in your container. Default is off however you’ll be able to configure it to be on with the TTL time being item-specific or for all gadgets within the container;
  • Geospatial Configuration, that is used to question gadgets primarily based on location;
    • Geography, represents information in a round-earth coordinate system;
    • Geometry, represents information in a flat coordinate system.
  • Partition Key, the partition key used to scale your partition;
  • Indexing Coverage, units how the container applies the indexes to its gadgets. You could embody or exclude properties, set the consistency mode, robotically apply the indexes, and so on..

Triggers, Saved Procedures, and user-defined capabilities with Cosmos DB

 

Azure Cosmos DB gives a transactional solution to execute code as a way to outline Triggers, Saved Procedures, and Capabilities. You may outline these Triggers, Saved Procedures, and Capabilities by the Azure Portal, Javascript Question API for Cosmos DB, or Cosmos DB SQL API consumer SDKs.

 

Azure Cosmos DB has two varieties of triggers,

  • Pre-trigger which is executed earlier than the information has modified;
  • Publish-trigger which is executed after the information has modified.

Change Feed Notifications with Cosmos DB

 

The Azure Cosmos DB Change Feed Notifications is a service that displays the modifications occurring amongst all containers and distributes occasions, triggered by these modifications, throughout a number of customers.  

 

The Change Feed Notifications may also be scaled-up or scaled-down alongside the Cosmos Db Containers and its foremost parts are those as follows,

  • The monitored container, which is the container that when any insert or replace is executed the operations are mirrored within the change feed;
  • The lease container, whereas it shops the states and coordinates the change feed processor;
  • The host, internet hosting the change feed processor;
  • The delegate, which is the code executed when triggered by any occasion within the change feed notifications.

The change feed processor could also be hosted amongst Azure companies that assist long-running duties, like Azure WebJobs, Azure Digital Machines, Azure Kubernetes Providers, and Azure .Web hosted companies.

 

Sensible Pattern

 

 

Examine of the case: we’re going to create a Database schema to characterize these courses bellow, don’t forget that your Id subject have to be specified and be a novel string

  1. public class Particular person  
  2.    {  
  3.        [JsonProperty(PropertyName = “id”)]  
  4.        public string Id { getset; }  
  5.        public DateTime BirthDate { getset; }  
  6.        public string Title { getset; }  
  7.        public string LastName { getset; }  
  8.        public Handle Handle { getset; }  
  9.        public Car Car { getset; }  
  10.    }  
  11.    public class Handle  
  12.    {  
  13.        public int Id { getset; }  
  14.        public string Metropolis { getset; }  
  15.        public string StreetAndNumber { getset; }  
  16.   
  17.    }  
  18.    public class Car  
  19.    {  
  20.        public int Id { getset; }  
  21.        public int 12 months { getset; }  
  22.        public string Mannequin { getset; }  
  23.        public string Make { getset; }  
  24.   
  25.    }  

Creating Azure Cosmos DB utilizing Azure Portal

 

In your Azure Portal, seek for the Azure Cosmos DB product after which click on on Add. Fill the Fundamentals, Networking, Backup coverage, Encryption, and Tags varieties then create it.

Right here we will probably be utilizing the Core SQL API and naming the Cosmos DB as sampleazurecosmosdb.

 

Road To AZ-204 - Developing Solutions That Use Cosmos DB Storage

 

After Profitable deployment, entry your Cosmos DB useful resource as a way to get your endpoint URI and the first key for additional utilization.

 

Road To AZ-204 - Developing Solutions That Use Cosmos DB Storage

 

Validate your empty Knowledge Explorer

 

Road To AZ-204 - Developing Solutions That Use Cosmos DB Storage

 

Creating an Azure Cosmos DB Database utilizing C#

 

Necessities

  1. Create a brand new Console Software
  2. Set up Nuget Microsoft.Azure.Cosmos
Name the CreateDatabaseIfNotExistsAsync methodology out of your Cosmos Shopper to create your database,

  1. class Program  
  2.    {  
  3.        personal static readonly string endpointUri = “https://sampleazurecosmosdb.paperwork.azure.com:443/”;  
  4.        personal static readonly string primaryKey = “BD43cPOWtjdSsSeBTpy2rbJLIW4lMzhGoNkiVKX6y32cTQ2E2f139J0r8xxS3YR8Sy1bQywls9ByISabRjuaUQ==”;  
  5.        public static async Process Major(string[] args)  
  6.        {  
  7.            utilizing (CosmosClient consumer = new CosmosClient(endpointUri, primaryKey))  
  8.            {  
  9.                DatabaseResponse databaseResponse = await consumer.CreateDatabaseIfNotExistsAsync(“SampleCosmosDB”);  
  10.                Database sampleDatabase = databaseResponse.Database;  
  11.   
  12.                await Console.Out.WriteLineAsync($“Database Id:t{sampleDatabase.Id}”);  
  13.            }  
  14.        }  
  15.    }  
Road To AZ-204 - Developing Solutions That Use Cosmos DB Storage

 

Validate your Knowledge Explorer by Azure Portal

 

Road To AZ-204 - Developing Solutions That Use Cosmos DB Storage

Creating an Azure Cosmos DB Partitioned Container utilizing C#

 

Set your indexing coverage in your container properties, and name the CreateContainerIfNotExistsAsync methodology out of your database object, right here we additionally go the specified throughput alongside the container properties.

  1. IndexingPolicy indexingPolicy = new IndexingPolicy  
  2. {  
  3.     IndexingMode = IndexingMode.Constant,  
  4.     Automated = true,  
  5.     IncludedPaths =  
  6.     {  
  7.         new IncludedPath  
  8.         {  
  9.             Path = “/*”  
  10.         }  
  11.     }  
  12. };  
  13. var containerProperties = new ContainerProperties(“Particular person”“/Title”)  
  14. {  
  15.     IndexingPolicy = indexingPolicy  
  16. };  
  17. var sampleResponse = await sampleDatabase.CreateContainerIfNotExistsAsync(containerProperties, 10000);  
  18. var customContainer = sampleResponse.Container;  
  19. await Console.Out.WriteLineAsync($“Pattern Container Id:t{customContainer.Id}”);  

Road To AZ-204 - Developing Solutions That Use Cosmos DB Storage

 

Validate your Knowledge Explorer by Azure Portal

 

Road To AZ-204 - Developing Solutions That Use Cosmos DB Storage

 

Including information to your Azure Cosmos DB container utilizing C#

 

We will probably be including a brand new Particular person as follows,

  1. personal static Particular person GetPerson()  
  2.        {  
  3.            return new Particular person  
  4.            {  
  5.                BirthDate = DateTime.Now.AddYears(30),  
  6.                Id = “10.Thiago”,  
  7.                Title = “Thiago”,  
  8.                LastName = “Araujo”,  
  9.                Car = new Car  
  10.                {  
  11.                    Id = 2,  
  12.                    Make = “Audi”,  
  13.                    Mannequin = “TT”,  
  14.                    12 months = 2020  
  15.                },  
  16.                Handle = new Handle  
  17.                {  
  18.                    Id = 12,  
  19.                    Metropolis = “Lisbon”,  
  20.                    StreetAndNumber = “Rua 25 de Abril, 4”  
  21.                }  
  22.            };  
  23.        }  

Out of your Container, name the CreateItemAsync methodology and go the individual object alongside its partition key.

  1. var createPersonResponse = await customContainer.CreateItemAsync<Particular person>(GetPerson(), new PartitionKey(GetPerson().Title));  
  2. await Console.Out.WriteLineAsync($“Created individual with Id:t{createPersonResponse.Useful resource.Id}. Consuming complete of t{createPersonResponse.RequestCharge} RUs”);   
Road To AZ-204 - Developing Solutions That Use Cosmos DB Storage

 

Validate your Knowledge Explorer by Azure Portal

 

Road To AZ-204 - Developing Solutions That Use Cosmos DB Storage 

Creating an Azure Cosmos DB Database utilizing Azure CLI

 

Creating an Azure Cosmos DB Partitioned Container utilizing Azure CLI

Setting variables

  1. $resourceGroup = “your useful resource group”  
  2. $cosmosDBAccount=“samplecosmosaccount”  
  3. $databaseName =“sampleclidatabase”  
  4. $containerName =“samplecontainername”  
  5. $partitionKey = “/Title”  

Creating Cosmos DB Account

 

Road To AZ-204 - Developing Solutions That Use Cosmos DB Storage

 

Creating Cosmos DB Database

 

Road To AZ-204 - Developing Solutions That Use Cosmos DB Storage

 

Creating Cosmos DB Container

 

Road To AZ-204 - Developing Solutions That Use Cosmos DB Storage

 

Checking Azure Portal 

 

Road To AZ-204 - Developing Solutions That Use Cosmos DB Storage

 

Scaling Containers 

 

Inside your Azure Cosmos useful resource, go to Containers after which Scale. Configure your settings and click on on Save

 

Road To AZ-204 - Developing Solutions That Use Cosmos DB Storage

 

Making a Change feed notification

 

Right here I used Cosmos DB Emulator to have the change feed notification working.

 

Create databases and containers

  1. CosmosClient cosmosClient = new CosmosClientBuilder(endpointUri, primaryKey).Construct();  
  2.   
  3. Database database = await cosmosClient.CreateDatabaseIfNotExistsAsync(databaseName);  
  4.   
  5. await database.CreateContainerIfNotExistsAsync(new ContainerProperties(sourceContainerName, “/id”));  
  6.   
  7. await database.CreateContainerIfNotExistsAsync(new ContainerProperties(leaseContainerName, “/id”));  

Begin Change Feed Processor

  1. Container leaseContainer = cosmosClient.GetContainer(databaseName, leaseContainerName);  
  2.            ChangeFeedProcessor changeFeedProcessor = cosmosClient.GetContainer(databaseName, sourceContainerName)  
  3.                .GetChangeFeedProcessorBuilder<Particular person>(processorName: “changeFeedSample”, HandleChangesAsync)  
  4.                    .WithInstanceName(“consoleHost”)  
  5.                    .WithLeaseContainer(leaseContainer)  
  6.                    .Construct();  
  7.   
  8.            await changeFeedProcessor.StartAsync();  

Monitor Adjustments from Supply Container

  1. static async Process HandleChangesAsync(IReadOnlyCollection<Particular person> modifications, CancellationToken cancellationToken)  
  2.      {  
  3.          Console.WriteLine(“Began dealing with modifications…”);  
  4.          foreach (Particular person merchandise in modifications)  
  5.          {  
  6.              Console.WriteLine($“Detected operation for individual with id {merchandise.Id}, created at {merchandise.CreationDate}.”);  
  7.                
  8.              await Process.Delay(10);  
  9.          }  
  10.   
  11.          Console.WriteLine(“Completed dealing with modifications.”);  
  12.      }  

Create Gadgets within the Supply Container

  1. personal static async Process GenerateItemsAsync(CosmosClient cosmosClient)  
  2.        {  
  3.            Container sourceContainer = cosmosClient.GetContainer(databaseName, sourceContainerName);  
  4.            whereas (true)  
  5.            {  
  6.                Console.WriteLine(“Enter a quantity of individuals to insert in the container or ‘exit’ to cease:”);  
  7.                string command = Console.ReadLine();  
  8.                if (“exit”.Equals(command, StringComparison.InvariantCultureIgnoreCase))  
  9.                {  
  10.                    Console.WriteLine();  
  11.                    break;  
  12.                }  
  13.   
  14.                if (int.TryParse(command, out int itemsToInsert))  
  15.                {  
  16.                    Console.WriteLine($“Producing {itemsToInsert} individuals…”);  
  17.                    for (int i = 0; i < itemsToInsert; i++)  
  18.                    {  
  19.                        var individual = GetPerson();  
  20.                        await sourceContainer.CreateItemAsync<Particular person>(individual,  
  21.                            new PartitionKey(individual.Id));  
  22.                    }  
  23.                }  
  24.            }  
  25.   
  26.        }  

Full Code

  1. class Program  
  2.     {  
  3.         personal static readonly string endpointUri = “https://localhost:8081/”;  
  4.         personal static readonly string primaryKey = “C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==”;  
  5.         personal static readonly string databaseName = “sampleDatabase”;  
  6.         personal static readonly string sourceContainerName = “sampleSourceContainer”;  
  7.         personal static readonly string leaseContainerName = “sampleLeaseContainer”;  
  8.         static async Process Major(string[] args)  
  9.         {  
  10.             CosmosClient cosmosClient = new CosmosClientBuilder(endpointUri, primaryKey).Construct();  
  11.   
  12.             Database database = await cosmosClient.CreateDatabaseIfNotExistsAsync(databaseName);  
  13.   
  14.             await database.CreateContainerIfNotExistsAsync(new ContainerProperties(sourceContainerName, “/id”));  
  15.   
  16.             await database.CreateContainerIfNotExistsAsync(new ContainerProperties(leaseContainerName, “/id”));  
  17.   
  18.             ChangeFeedProcessor processor = await StartChangeFeedProcessorAsync(cosmosClient);  
  19.   
  20.             await GenerateItemsAsync(cosmosClient);  
  21.         }  
  22.   
  23.         personal static async Process<ChangeFeedProcessor> StartChangeFeedProcessorAsync(  
  24.     CosmosClient cosmosClient)  
  25.         {  
  26.   
  27.             Container leaseContainer = cosmosClient.GetContainer(databaseName, leaseContainerName);  
  28.             ChangeFeedProcessor changeFeedProcessor = cosmosClient.GetContainer(databaseName, sourceContainerName)  
  29.                 .GetChangeFeedProcessorBuilder<Particular person>(processorName: “changeFeedSample”, HandleChangesAsync)  
  30.                     .WithInstanceName(“consoleHost”)  
  31.                     .WithLeaseContainer(leaseContainer)  
  32.                     .Construct();  
  33.   
  34.             Console.WriteLine(“Beginning Change Feed Processor…”);  
  35.             await changeFeedProcessor.StartAsync();  
  36.             Console.WriteLine(“Change Feed Processor began.”);  
  37.             return changeFeedProcessor;  
  38.         }  
  39.         static async Process HandleChangesAsync(IReadOnlyCollection<Particular person> modifications, CancellationToken cancellationToken)  
  40.         {  
  41.             Console.WriteLine(“Began dealing with modifications…”);  
  42.             foreach (Particular person merchandise in modifications)  
  43.             {  
  44.                 Console.WriteLine($“Detected operation for individual with id {merchandise.Id}, created at {merchandise.CreationDate}.”);  
  45.                   
  46.                 await Process.Delay(10);  
  47.             }  
  48.   
  49.             Console.WriteLine(“Completed dealing with modifications.”);  
  50.         }  
  51.   
  52.         personal static async Process GenerateItemsAsync(CosmosClient cosmosClient)  
  53.         {  
  54.             Container sourceContainer = cosmosClient.GetContainer(databaseName, sourceContainerName);  
  55.             whereas (true)  
  56.             {  
  57.                 Console.WriteLine(“Enter a quantity of individuals to insert in the container or ‘exit’ to cease:”);  
  58.                 string command = Console.ReadLine();  
  59.                 if (“exit”.Equals(command, StringComparison.InvariantCultureIgnoreCase))  
  60.                 {  
  61.                     Console.WriteLine();  
  62.                     break;  
  63.                 }  
  64.   
  65.                 if (int.TryParse(command, out int itemsToInsert))  
  66.                 {  
  67.                     Console.WriteLine($“Producing {itemsToInsert} individuals…”);  
  68.                     for (int i = 0; i < itemsToInsert; i++)  
  69.                     {  
  70.                         var individual = GetPerson();  
  71.                         await sourceContainer.CreateItemAsync<Particular person>(individual,  
  72.                             new PartitionKey(individual.Id));  
  73.                     }  
  74.                 }  
  75.             }  
  76.   
  77.         }  
  78.         personal static Particular person GetPerson()  
  79.         {  
  80.             Random random = new Random();  
  81.             return new Particular person  
  82.             {  
  83.                 BirthDate = DateTime.Now.AddYears(30),  
  84.                 Id = random.Subsequent() + “Thiago”,  
  85.                 Title = “Thiago”,  
  86.                 LastName = “Araujo”,  
  87.                 CreationDate = DateTime.Now,  
  88.                 Car = new Car  
  89.                 {  
  90.                     Id = random.Subsequent(),  
  91.                     Make = “Audi”,  
  92.                     Mannequin = “TT”,  
  93.                     12 months = random.Subsequent()  
  94.                 },  
  95.                 Handle = new Handle  
  96.                 {  
  97.                     Id = random.Subsequent(),  
  98.                     Metropolis = “Lisbon”,  
  99.                     StreetAndNumber = “Rua 25 de Abril, 4”  
  100.                 }  
  101.             };  
  102.         }  
  103.     }  
  104.     public class Particular person  
  105.     {  
  106.         [JsonProperty(PropertyName = “id”)]  
  107.         public string Id { getset; }  
  108.         public DateTime BirthDate { getset; }  
  109.         public string Title { getset; }  
  110.         public string LastName { getset; }  
  111.         public Handle Handle { getset; }  
  112.         public Car Car { getset; }  
  113.         public DateTime CreationDate { getset; }  
  114.     }  
  115.     public class Handle  
  116.     {  
  117.         public int Id { getset; }  
  118.         public string Metropolis { getset; }  
  119.         public string StreetAndNumber { getset; }  
  120.   
  121.     }  
  122.     public class Car  
  123.     {  
  124.         public int Id { getset; }  
  125.         public int 12 months { getset; }  
  126.         public string Mannequin { getset; }  
  127.         public string Make { getset; }  
  128.   
  129.     }  

Consequence

 

Road To AZ-204 - Developing Solutions That Use Cosmos DB Storage

 

Road To AZ-204 - Developing Solutions That Use Cosmos DB Storage

 

Road To AZ-204 - Developing Solutions That Use Cosmos DB Storage

 

Creating Saved Procedures

  1.   
  2. operate pattern(prefix) {  
  3.     var assortment = getContext().getCollection();  
  4.   
  5.       
  6.     var isAccepted = assortment.queryDocuments(  
  7.         assortment.getSelfLink(),  
  8.         ‘SELECT * FROM root r’,  
  9.     operate (err, feed, choices) {  
  10.         if (err) throw err;  
  11.   
  12.           
  13.           
  14.         if (!feed || !feed.size) {  
  15.             var response = getContext().getResponse();  
  16.             response.setBody(‘no docs discovered’);  
  17.         }  
  18.         else {  
  19.             var response = getContext().getResponse();  
  20.             var physique = { prefix: prefix, feed: feed[0] };  
  21.             response.setBody(JSON.stringify(physique));  
  22.         }  
  23.     });  
  24.   
  25.     if (!isAccepted) throw new Error(‘The question was not accepted by the server.’);  
  26. }  


Executing

 

Road To AZ-204 - Developing Solutions That Use Cosmos DB Storage

 

Creating Triggers

 

Pre-Set off

  1. operate validateItemTimestamp() {  
  2.     var context = getContext();  
  3.     var request = context.getRequest();  
  4.   
  5.       
  6.     var itemToCreate = request.getBody();  
  7.   
  8.       
  9.     if (!(“triggerTime” in itemToCreate)) {  
  10.         var ts = new Date();  
  11.         itemToCreate[“triggerTime”] = ts.getTime();  
  12.     }  
  13.   
  14.       
  15.     request.setBody(itemToCreate);  
  16. }  

Publish-Set off 

  1. operate updateMetadata() {  
  2. var context = getContext();  
  3. var container = context.getCollection();  
  4. var response = context.getResponse();  
  5.   
  6.   
  7. var createdItem = response.getBody();  
  8.   
  9.   
  10. var filterQuery = ‘SELECT * FROM root r WHERE r.id = “_metadata”‘;  
  11. var settle for = container.queryDocuments(container.getSelfLink(), filterQuery,  
  12.     updateMetadataCallback);  
  13. if(!settle for) throw “Unable to replace metadata, abort”;  
  14. }  
  15. operate updateMetadataCallback(err, gadgets, responseOptions) {  
  16.     if(err) throw new Error(“Error” + err.message);  
  17.         if(gadgets.size != 1) throw ‘Unable to discover metadata doc’;  
  18.   
  19.         var metadataItem = gadgets[0];  
  20.   
  21.           
  22.         metadataItem.createdItems += 1;  
  23.         metadataItem.createdNames += ” Publish set off”;  
  24.         var settle for = container.replaceDocument(metadataItem._self,  
  25.             metadataItem, operate(err, itemReplaced) {  
  26.                     if(err) throw “Unable to replace metadata, abort”;  
  27.             });  
  28.         if(!settle for) throw “Unable to replace metadata, abort”;  
  29.         return;  
  30. }  

Exterior References

Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button