In this lab, you will gain experience using C# and Visual Studio to connect to and use Cosmos DB. You will RDP into a Windows VM set up with Visual Studio and update a pre-built solution with the appropriate Cosmos DB C# code to connect to Cosmos DB, upload documents, and use the SQL API to query documents. When this is complete, you will run a console application to see everything working and can go back to the Azure portal to verify the documents were saved. Upon completion of the lab, you will have gained the experience required to work with Cosmos DB using C#.
Learning Objectives
Successfully complete this lab by achieving the following learning objectives:
- RDP into the VM and open the Visual Studio solution.
RDP login:
See credentials in the credentials section of the lab window.
PowerShell to run:
$url = "https://github.com/ACloudGuru-Resources/content-azure-labs/blob/master/zips/Azure-LearningActivity-Cosmos%20DBv2.zip?raw=true" $zipfile = "C:Userscloud_userDesktopAzure-LearningActivity-Cosmos DBv2.zip" $folder = "C:Userscloud_userDesktop" [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 Invoke-WebRequest -UseBasicParsing -OutFile $zipfile $url Expand-Archive -LiteralPath $zipfile -DestinationPath $folder Remove-Item -Path $zipfile
- Update the Visual Studio solution and run the console app.
Create a New Container in the Azure Portal
- In the Azure portal, click All resources.
- Select the Azure Cosmos DB account resource in the list.
- Click Add Container.
- In the Add Container pane, set the following values:
- Database id: Create new, and name it db1
- Container id: collection1
- Partition key: /Partition
- Throughput: 400
- Click OK.
Update the Visual Studio Code on VM
- Back on the virtual machine, in the Visual Studio window, double-click Program.cs in the right-hand menu to open it.
- In the
Program
class, we need to enter a couple pieces of missing information:EndpointUrl
andPrimaryKey
. In the Azure Portal, head to the Overview section for our Cosmos DB account. - Copy the listed URI.
- Back in Visual Studio, paste it in as the
EndpointUrl
value. - In the Azure portal, scroll down and click Keys (under the Settings heading).
- Copy the listed primary key.
- Back in Visual Studio, paste it in as the
PrimaryKey
value. - Click the disk icon to save the code.
- Click the play button icon to run the console app.
- Back in the Azure portal, scroll down and click Document Explorer (under the Containers heading).
- Click Open Data Explorer.
- Click collection1.
- Click Documents. We should see two documents listed, which means we were successful.