Skip to content

Commit

Permalink
Add initial project setup for Azure Cosmos DB integration
Browse files Browse the repository at this point in the history
Added solution and project files for DotnetAzureCosmosDb, including configuration for Debug and Release builds. Configured logging and Cosmos DB settings in `appsettings.json` and `appsettings.Development.json`. Implemented core project structure with `Program.cs` for app setup, `ApiResponse.cs` for API responses, and `launchSettings.json` for launch configuration. Added `Student` model, `IStudentService` interface, and `StudentService` implementation for managing student entities in Cosmos DB. Created `StudentController` for API endpoints and `CosmosDbServiceExtensions` for Cosmos DB client initialization. Added HTTP request definitions in `DotnetAzureCosmosDb.http`.
  • Loading branch information
Clifftech123 committed Dec 13, 2024
1 parent 1083b75 commit 2bd305c
Show file tree
Hide file tree
Showing 14 changed files with 492 additions and 0 deletions.
22 changes: 22 additions & 0 deletions DotnetAzureCosmosDb/DotnetAzureCosmosDb.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.12.35506.116 d17.12
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotnetAzureCosmosDb", "DotnetAzureCosmosDb\DotnetAzureCosmosDb.csproj", "{0B1346AB-9EEA-4A76-B885-6A25EB42C427}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0B1346AB-9EEA-4A76-B885-6A25EB42C427}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0B1346AB-9EEA-4A76-B885-6A25EB42C427}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0B1346AB-9EEA-4A76-B885-6A25EB42C427}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0B1346AB-9EEA-4A76-B885-6A25EB42C427}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace DotnetAzureCosmosDb.Contracts
{
public class ApiResponse
{
public string Message { get; set; }
public bool IsSuccess { get; set; }
public object Result { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace DotnetAzureCosmosDb.Contracts
{
public interface IStudentService
{
Task<ApiResponse> AddStudentAsync(CreateStudentDto student);
Task<ApiResponse> GetStudentByIdAsync(string id);
Task<ApiResponse> GetAllStudentsAsync(string qurey);
Task<ApiResponse> UpdateStudentAsync(string id, UpdateStudentDto student);
Task<ApiResponse> DeleteStudentAsync(string id);
}
}
30 changes: 30 additions & 0 deletions DotnetAzureCosmosDb/DotnetAzureCosmosDb/Contracts/StudentDTOs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using Newtonsoft.Json;

namespace DotnetAzureCosmosDb.Contracts
{

public record CreateStudentDto
{
[JsonProperty(PropertyName = "name")]
public required string Name { get; init; }

[JsonProperty(PropertyName = "email")]
public required string Email { get; init; }

[JsonProperty(PropertyName = "age")]
public int Age { get; init; }
}


public record UpdateStudentDto
{

public required string Name { get; init; }
[JsonProperty(PropertyName = "email")]
public required string Email { get; init; }
[JsonProperty(PropertyName = "age")]
public int Age { get; init; }
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
using DotnetAzureCosmosDb.Contracts;
using Microsoft.AspNetCore.Mvc;

namespace DotnetAzureCosmosDb.Controllers
{
/// <summary>
/// Controller for managing student entities.
/// </summary>
[ApiController]
[Route("api/")]
public class StudentController : ControllerBase
{
private readonly IStudentService _studentService;

/// <summary>
/// Initializes a new instance of the <see cref="StudentController"/> class.
/// </summary>
/// <param name="studentService">The student service.</param>
public StudentController(IStudentService studentService)
{
_studentService = studentService;
}

/// <summary>
/// Adds a new student asynchronously.
/// </summary>
/// <param name="student">The student to add.</param>
/// <returns>An <see cref="IActionResult"/> indicating the result of the operation.</returns>
[HttpPost("student")]
public async Task<IActionResult> AddStudentAsync([FromBody] CreateStudentDto student)
{
var response = await _studentService.AddStudentAsync(student);
if (response.IsSuccess)
{
return Ok(response);
}
return BadRequest(response);
}

/// <summary>
/// Gets all students asynchronously.
/// </summary>
/// <returns>An <see cref="IActionResult"/> containing the list of students.</returns>
[HttpGet("students")]
public async Task<IActionResult> GetAllStudents()
{
var students = await _studentService.GetAllStudentsAsync("SELECT * FROM c");
return Ok(students);
}

/// <summary>
/// Gets a student by ID asynchronously.
/// </summary>
/// <param name="id">The ID of the student.</param>
/// <returns>An <see cref="IActionResult"/> containing the student.</returns>
[HttpGet("student/{id}")]
public async Task<IActionResult> GetStudentByIdAsync(string id)
{
var student = await _studentService.GetStudentByIdAsync(id);
return Ok(student);
}

/// <summary>
/// Updates a student asynchronously.
/// </summary>
/// <param name="id">The ID of the student to update.</param>
/// <param name="student">The updated student data.</param>
/// <returns>An <see cref="IActionResult"/> indicating the result of the operation.</returns>
[HttpPut("student")]
public async Task<IActionResult> UpdateStudentAsync(string id, [FromBody] UpdateStudentDto student)
{
var response = await _studentService.UpdateStudentAsync(id, student);
if (response.IsSuccess)
{
return Ok(response);
}
return BadRequest(response);
}

/// <summary>
/// Deletes a student asynchronously.
/// </summary>
/// <param name="id">The ID of the student to delete.</param>
/// <returns>An <see cref="IActionResult"/> indicating the result of the operation.</returns>
[HttpDelete("student/{id}")]
public async Task<IActionResult> DeleteStudentAsync(string id)
{
var response = await _studentService.DeleteStudentAsync(id);
if (response.IsSuccess)
{
return Ok(response);
}
return BadRequest(response);
}
}
}
16 changes: 16 additions & 0 deletions DotnetAzureCosmosDb/DotnetAzureCosmosDb/DotnetAzureCosmosDb.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0" />
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.46.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@DotnetAzureCosmosDb_HostAddress = http://localhost:5176

GET {{DotnetAzureCosmosDb_HostAddress}}/weatherforecast/
Accept: application/json

###
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using DotnetAzureCosmosDb.Services;

namespace DotnetAzureCosmosDb.Extensions
{
public static class CosmosDbServiceExtensions
{
public static async Task<StudentService> InitializeCosmosClientInstanceAsync(this IConfigurationSection configurationSection)
{
var databaseName = configurationSection["DatabaseName"];
var containerName = configurationSection["ContainerName"];
var account = configurationSection["Account"];
var key = configurationSection["Key"];

var client = new Microsoft.Azure.Cosmos.CosmosClient(account, key);
var database = await client.CreateDatabaseIfNotExistsAsync(databaseName);
await database.Database.CreateContainerIfNotExistsAsync(containerName, "/id");

return new StudentService(client, databaseName, containerName);
}
}
}
23 changes: 23 additions & 0 deletions DotnetAzureCosmosDb/DotnetAzureCosmosDb/Models/Student.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using Newtonsoft.Json;

namespace DotnetAzureCosmosDb.Models
{
public class Student
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }

[JsonProperty(PropertyName = "name")]

public string Name { get; set; }


[JsonProperty(PropertyName = "email")]

public string Email { get; set; }


[JsonProperty(PropertyName = "age")]
public int Age { get; set; }
}
}
35 changes: 35 additions & 0 deletions DotnetAzureCosmosDb/DotnetAzureCosmosDb/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using DotnetAzureCosmosDb.Contracts;
using DotnetAzureCosmosDb.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();


builder.Services.AddSwaggerGen();

// Adding services to the container
builder.Services.AddSingleton<IStudentService>(builder.Configuration.GetSection("CosmosDb").InitializeCosmosClientInstanceAsync().GetAwaiter().GetResult());


var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.UseSwaggerUI();
app.UseSwagger();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:5176",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:7279;http://localhost:5176",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Loading

0 comments on commit 2bd305c

Please sign in to comment.