Skip to content

Instantly share code, notes, and snippets.

@ankittyagii
Last active January 4, 2020 02:40
Show Gist options
  • Save ankittyagii/38453f80ac1e8d3365248e8bb1dbe798 to your computer and use it in GitHub Desktop.
Save ankittyagii/38453f80ac1e8d3365248e8bb1dbe798 to your computer and use it in GitHub Desktop.
Cosmos DB SQL API Demo C# Code Snippets
public static class Common
{
public const string EndpointUrl = "https://<your-account>.documents.azure.com:443/";
public const string AuthorizationKey = "<your-account-key>";
public const string DatabaseId = "FamilyDatabase";
public const string ContainerId = "FamilyContainer";
public const string employeesPartitionKey = "/department";
//Query
public const string GetAllEmployeeSqlQuery = "Select * from employees";
public const string GetEmployeeByIdSqlQuery = "Select * from {0} where EmployeeId={1}";
}
public class EmployeeModel
{
[JsonProperty(PropertyName ="id")]
public string Id { get; set; }
public string EmployeeId { get; set; }
public string EmployeeName { get; set; }
[JsonProperty(PropertyName ="department")]
public string Department { get; set; }
public string Role { get; set; }
public string Band { get; set; }
public double Salary { get; set; }
public string Location { get; set; }
public string EmailId { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Pincode { get; set; }
public string CountryCode { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Cosmos_Demo.Helpers;
using Cosmos_Demo.Models;
using Microsoft.Azure.Cosmos;
namespace Cosmos_Demo.Services
{
public class CosmosClientService
{
public CosmosClient _cosmosClient;
public CosmosClientService()
{
_cosmosClient = new CosmosClient(Common.EndpointUrl, Common.AuthorizationKey);
}
public async Task<string> GetDbOrCreateIfDbNotExist(string databaseId)
{
try
{
var database = _cosmosClient.GetDatabase(databaseId);
if (database != null)
{
var response = _cosmosClient.CreateDatabaseIfNotExistsAsync(database.Id, null, null).Result;
return response.Database.Id;
}
else
{
return database.Id;
}
}
catch (Exception ex)
{
throw;
}
}
public async Task<string> GetContainerOrCreateContainerIfNotExist(string databaseId, string containerId)
{
try
{
var container = GetContainer(databaseId, containerId);
if (container != null)
{
ContainerProperties containerProperies = new ContainerProperties(Common.ContainerId, Common.employeesPartitionKey);
var response = _cosmosClient.GetDatabase(databaseId).CreateContainerIfNotExistsAsync(containerProperies).Result;
return response.Container.Id;
}
else
return container.Id;
}
catch (CosmosException ex )
{
return ex.ToString();
throw;
}
catch(Exception ex)
{
return ex.ToString();
}
}
public Container GetContainer(string databaseid, string containerId)
{
return _cosmosClient.GetContainer(databaseid, containerId);
}
public async Task<string> InsertData(Container objContainer, EmployeeModel employeeModel)
{
try
{
//CheckIfExist
ItemResponse<EmployeeModel> objModel = objContainer.ReadItemAsync<EmployeeModel>(employeeModel.Id, new PartitionKey(employeeModel.Department)).Result;
if (objModel != null)
{
objModel = null;
return "Record Already Exists";
}
ItemResponse<EmployeeModel> itemResponse = objContainer.CreateItemAsync(employeeModel, new PartitionKey(employeeModel.Department)).Result;
if (itemResponse != null)
{
return "Inserted Sucessfully";
}
else
{
return "Failed";
}
}
catch (Exception ex)
{
throw;
}
}
public async Task<List<EmployeeModel>> GetAllDataAsync(Container objContainer)
{
try
{
List<EmployeeModel> lstModel = new List<EmployeeModel>();
QueryDefinition queryDefination = new QueryDefinition(Common.GetAllEmployeeSqlQuery);
var query = objContainer.GetItemQueryIterator<EmployeeModel>(queryDefination);
while (query.HasMoreResults)
{
var response = query.ReadNextAsync().Result;
foreach (var item in response)
{
lstModel.Add(item);
}
}
return lstModel;
}
catch (Exception)
{
throw;
}
}
public async Task<EmployeeModel> UpdateData(EmployeeModel objModel, Container objContainer, string id)
{
return objContainer.UpsertItemAsync(objModel, new PartitionKey(objModel.Department)).Result;
}
public async Task<EmployeeModel> DeleteDataById(string partitionKey, Container objContainer, string id)
{
return objContainer.DeleteItemAsync<EmployeeModel>(id, new PartitionKey(partitionKey)).Result;
}
}
}
using System;
using Cosmos_Demo.Services;
using Cosmos_Demo.Models;
using Microsoft.Azure.Cosmos;
using Cosmos_Demo.Helpers;
using Newtonsoft.Json;
namespace Cosmos_Demo
{
class Program
{
private static CosmosClientService _clientService;
public static void Main(string[] args)
{
RunProgram();
}
public static async void RunProgram()
{
Console.WriteLine("Hello World! from Cosmos World - Anvitte");
_clientService = new CosmosClientService();
//Get Database If Exist or Create Database.
Console.WriteLine("---------------Database creation Module start---------------------------");
var databaseId = await _clientService.GetDbOrCreateIfDbNotExist(Common.DatabaseId);
Console.WriteLine("Database Id {0}", databaseId);
Console.WriteLine("---------------Database creation Module Finish");
Console.WriteLine("---------------Container Creation Module Start--------------------------");
var containerId = await _clientService.GetContainerOrCreateContainerIfNotExist(databaseId, Common.ContainerId);
Console.WriteLine("Container Id {0}", containerId);
Console.WriteLine("---------------Container Creation Module finish-------------------------");
Console.WriteLine();
Console.WriteLine("---------------Get Container Object Module Start------------------------");
//Get Container Record
var objContainer = _clientService.GetContainer(databaseId, containerId);
Console.WriteLine("---------------Get Container Object Module finish-----------------------");
Console.WriteLine();
//Check Record if exist else Insert Record
Console.WriteLine("---------------Insert Module Start--------------------------------------");
Console.WriteLine("Ist record entered");
var result = await _clientService.InsertData(objContainer, new EmployeeModel()
{
EmployeeName = "Ankit Tyagi",
Location = "Riyadh, Saudi Arabia",
EmailId = "Ankittyagi366@gmail.com",
City = "Riyadh",
Address = "Abdul Aziz Dist.",
Department = "MAS",
Band = "B2",
Id = "1",
EmployeeId = "12312",
Country = "Saudi Arabia",
Role = "Senior Project Engineer"
});
Console.WriteLine(result);
Console.WriteLine("Second record entered");
var result1 = await _clientService.InsertData(objContainer, new EmployeeModel()
{
Id="3",
EmployeeName = "Manish Tyagi",
Location = "Delhi, india",
EmailId = "Manishtyagi12@gmail.com",
City = "delhi",
Address = "Shalimar Garden",
Department = "HR",
Band = "B1",
Salary = 152000,
EmployeeId = "12314",
Country = "India",
Role = "Senior Consultant",
CountryCode="+91",
Pincode="110001"
});
// Read All Record using query
Console.WriteLine("---------------Reading Module Start.............-----------------------");
Console.WriteLine();
var LstEmployeeModel = await _clientService.GetAllDataAsync(objContainer);
foreach (var item in LstEmployeeModel)
{
Console.WriteLine(JsonConvert.SerializeObject(item));
}
Console.WriteLine("---------------Reading Module Completed -------------------------------");
Console.WriteLine();
Console.WriteLine("---------------Updating Module start-----------------------------------");
//Updating Employeed model with salary and role
Console.WriteLine("Old Model before update");
Console.WriteLine(JsonConvert.SerializeObject(LstEmployeeModel[0]));
LstEmployeeModel[0].Salary = 200000;
LstEmployeeModel[0].Role = "Technical Lead";
Console.WriteLine("Updating ........");
var updatedModel = await _clientService.UpdateData(LstEmployeeModel[0], objContainer, LstEmployeeModel[0].Id);
Console.WriteLine("Updated ........");
Console.WriteLine("New Model after update");
Console.WriteLine(JsonConvert.SerializeObject(updatedModel));
Console.WriteLine("---------------Updating Module finish---------------------------------");
Console.Write("");
//Deleting
Console.WriteLine("---------------Deleting Module start----------------------------------");
var deletedItem = _clientService.DeleteDataById(LstEmployeeModel[1].Department, objContainer, LstEmployeeModel[1].Id);
Console.WriteLine("Deleted Item");
Console.WriteLine(JsonConvert.SerializeObject(LstEmployeeModel[1]));
Console.WriteLine("----------------Deleting Module Finish--------------------------------");
Console.WriteLine("Demo Completed");
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment