diff --git a/mohaymen-codestar-Team02/.Env.Example b/mohaymen-codestar-Team02/.Env.Example deleted file mode 100644 index 49daa90..0000000 --- a/mohaymen-codestar-Team02/.Env.Example +++ /dev/null @@ -1 +0,0 @@ -CONNECTION_STRING = "" \ No newline at end of file diff --git a/mohaymen-codestar-Team02/Controllers/AdminController.cs b/mohaymen-codestar-Team02/Controllers/AdminController.cs index 706804a..b9a8f4e 100644 --- a/mohaymen-codestar-Team02/Controllers/AdminController.cs +++ b/mohaymen-codestar-Team02/Controllers/AdminController.cs @@ -57,7 +57,7 @@ public async Task Delete([FromBody] DeleteUserDto request) { var user = new User { - Username = request.Username, + Username = request.Username }; ServiceResponse response = diff --git a/mohaymen-codestar-Team02/Controllers/DataAdminController.cs b/mohaymen-codestar-Team02/Controllers/DataAdminController.cs index f598ef3..189ab09 100644 --- a/mohaymen-codestar-Team02/Controllers/DataAdminController.cs +++ b/mohaymen-codestar-Team02/Controllers/DataAdminController.cs @@ -1,5 +1,9 @@ using Microsoft.AspNetCore.Mvc; +using mohaymen_codestar_Team02.Dto; +using mohaymen_codestar_Team02.Dto.GraphDTO; using mohaymen_codestar_Team02.Dto.StoreDataDto; +using mohaymen_codestar_Team02.Models; +using mohaymen_codestar_Team02.Services; using mohaymen_codestar_Team02.Services.DataAdminService; using mohaymen_codestar_Team02.Services.FileReaderService; @@ -7,23 +11,34 @@ namespace mohaymen_codestar_Team02.Controllers; public class DataAdminController : ControllerBase { - private readonly IDataAdminService _dataAdminService; private readonly IFileReader _fileReader; - public DataAdminController(IDataAdminService dataAdminService, IFileReader fileReader) + private readonly IDisplayDataService _dataService; + + public DataAdminController(IDataAdminService dataAdminService, IFileReader fileReader, + IDisplayDataService dataService) { _dataAdminService = dataAdminService; _fileReader = fileReader; + _dataAdminService = dataAdminService; } + [HttpPost("DataSets")] public async Task StoreNewDataSet([FromForm] StoreDataDto storeDataDto) { - var edgeFile = _fileReader.Read(storeDataDto.EdgeFile); - var vertexFile = _fileReader.Read(storeDataDto.VertexFile); - var response = await _dataAdminService.StoreData(edgeFile, vertexFile, storeDataDto.DataName, - Path.GetFileName(storeDataDto.EdgeFile.FileName), Path.GetFileName(storeDataDto.VertexFile.FileName), - storeDataDto.CreatorUserName); - return StatusCode((int)response.Type, response); + try + { + var edgeFile = _fileReader.Read(storeDataDto.EdgeFile); + var vertexFile = _fileReader.Read(storeDataDto.VertexFile); + var response = await _dataAdminService.StoreData(edgeFile, vertexFile, storeDataDto.DataName, + Path.GetFileName(storeDataDto.EdgeFile.FileName), Path.GetFileName(storeDataDto.VertexFile.FileName), + storeDataDto.CreatorUserName); + return StatusCode((int)response.Type, response); + } + catch (FormatException e) + { + return BadRequest("your File is not on a correct format"); + } } [HttpGet("DataSets")] @@ -32,17 +47,26 @@ public void GetDataSetsList() } [HttpGet("DataSets/{dataSetName}")] - public void DisplayDataSetAsGraph(string dataSetName) + public async Task DisplayDataSetAsGraph(string dataSetName, + [FromQuery] string sourceEdgeIdentifierFieldName, [FromQuery] string destinationEdgeIdentifierFieldName, + [FromQuery] string vertexIdentifierFieldName) { + ServiceResponse response = + await _dataAdminService.DisplayGeraphData(dataSetName, sourceEdgeIdentifierFieldName, destinationEdgeIdentifierFieldName, vertexIdentifierFieldName); + response.Data.GraphName = dataSetName; + return StatusCode((int)response.Type, response); } + [HttpGet("DataSets/{dataSetName}/Vertices/{vertexId}")] - public void DisplayVertexDetails(string datasetName, int vertexId) + public async Task DisplayVertexDetails(string datasetName, int vertexId) { + return BadRequest(); } [HttpGet("DataSets/{dataSetName}/Edges/{edgeId}")] - public void DisplayEdgeDetails(string datasetName, int edgeId) + public async Task DisplayEdgeDetails(string datasetName, int edgeId) { + return BadRequest(); } } \ No newline at end of file diff --git a/mohaymen-codestar-Team02/Dto/GetGraphDto.cs b/mohaymen-codestar-Team02/Dto/GetGraphDto.cs new file mode 100644 index 0000000..40dade6 --- /dev/null +++ b/mohaymen-codestar-Team02/Dto/GetGraphDto.cs @@ -0,0 +1,9 @@ +namespace mohaymen_codestar_Team02.Dto; + +public class GetGraphDto +{ + public string databaseName; + public string sourceEdgeIdentifierFieldName; + public string destinationEdgeIdentifierFieldName; + public string vertexIdentifierFieldName; +} \ No newline at end of file diff --git a/mohaymen-codestar-Team02/Dto/GraphDTO/DetailDto.cs b/mohaymen-codestar-Team02/Dto/GraphDTO/DetailDto.cs new file mode 100644 index 0000000..400a15d --- /dev/null +++ b/mohaymen-codestar-Team02/Dto/GraphDTO/DetailDto.cs @@ -0,0 +1,6 @@ +namespace mohaymen_codestar_Team02.Dto.GraphDTO; + +public class DetailDto +{ + public Dictionary AttributeValue { get; init; } +} \ No newline at end of file diff --git a/mohaymen-codestar-Team02/Dto/GraphDTO/DisplayGraphDto.cs b/mohaymen-codestar-Team02/Dto/GraphDTO/DisplayGraphDto.cs new file mode 100644 index 0000000..e683de4 --- /dev/null +++ b/mohaymen-codestar-Team02/Dto/GraphDTO/DisplayGraphDto.cs @@ -0,0 +1,10 @@ +using mohaymen_codestar_Team02.Models; + +namespace mohaymen_codestar_Team02.Dto.GraphDTO; + +public class DisplayGraphDto +{ + public List Edges { get; init; } + public List Vertices { get; init; } + public string GraphName { get; set; } +} \ No newline at end of file diff --git a/mohaymen-codestar-Team02/Migrations/20240820151916_InitialCreatec.Designer.cs b/mohaymen-codestar-Team02/Migrations/20240820151916_InitialCreatec.Designer.cs new file mode 100644 index 0000000..34e4cbd --- /dev/null +++ b/mohaymen-codestar-Team02/Migrations/20240820151916_InitialCreatec.Designer.cs @@ -0,0 +1,414 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using mohaymen_codestar_Team02.Data; + +#nullable disable + +namespace mohaymen_codestar_Team02.Migrations +{ + [DbContext(typeof(DataContext))] + [Migration("20240820151916_InitialCreatec")] + partial class InitialCreatec + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.6") + .HasAnnotation("Proxies:ChangeTracking", false) + .HasAnnotation("Proxies:CheckEquality", false) + .HasAnnotation("Proxies:LazyLoading", true) + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.DataGroup", b => + { + b.Property("DataGroupId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("DataGroupId")); + + b.Property("CreateAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("bigint"); + + b.HasKey("DataGroupId"); + + b.HasIndex("UserId"); + + b.ToTable("DataSets"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeAttribute", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EdgeEntityId") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("EdgeEntityId"); + + b.ToTable("EdgeAttributes"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DataGroupId") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("DataGroupId") + .IsUnique(); + + b.ToTable("EdgeEntities"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeValue", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EdgeAttributeId") + .HasColumnType("bigint"); + + b.Property("ObjectId") + .IsRequired() + .HasColumnType("text"); + + b.Property("StringValue") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("EdgeAttributeId"); + + b.ToTable("EdgeValues"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.Role", b => + { + b.Property("RoleId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("RoleId")); + + b.Property("RoleType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("RoleId"); + + b.ToTable("Roles"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.User", b => + { + b.Property("UserId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("UserId")); + + b.Property("Email") + .IsRequired() + .HasColumnType("text"); + + b.Property("FirstName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("LastName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PasswordHash") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("bytea"); + + b.Property("Salt") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("bytea"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("UserId"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.UserRole", b => + { + b.Property("UserId") + .HasColumnType("bigint"); + + b.Property("RoleId") + .HasColumnType("bigint"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("UserRoles"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexAttribute", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("VertexEntityId") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("VertexEntityId"); + + b.ToTable("VertexAttributes"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DataGroupId") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("DataGroupId") + .IsUnique(); + + b.ToTable("VertexEntities"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexValue", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ObjectId") + .IsRequired() + .HasColumnType("text"); + + b.Property("StringValue") + .IsRequired() + .HasColumnType("text"); + + b.Property("VertexAttributeId") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("VertexAttributeId"); + + b.ToTable("VertexValues"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.DataGroup", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.User", "User") + .WithMany("DataSets") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeAttribute", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeEntity", "EdgeEntity") + .WithMany("EdgeAttributes") + .HasForeignKey("EdgeEntityId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("EdgeEntity"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeEntity", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.DataGroup", "DataGroup") + .WithOne("EdgeEntity") + .HasForeignKey("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeEntity", "DataGroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DataGroup"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeValue", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeAttribute", "EdgeAttribute") + .WithMany("EdgeValues") + .HasForeignKey("EdgeAttributeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("EdgeAttribute"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.UserRole", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.Role", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("mohaymen_codestar_Team02.Models.User", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexAttribute", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.VertexEAV.VertexEntity", "VertexEntity") + .WithMany("VertexAttributes") + .HasForeignKey("VertexEntityId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("VertexEntity"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexEntity", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.DataGroup", "DataGroup") + .WithOne("VertexEntity") + .HasForeignKey("mohaymen_codestar_Team02.Models.VertexEAV.VertexEntity", "DataGroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DataGroup"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexValue", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.VertexEAV.VertexAttribute", "VertexAttribute") + .WithMany("VertexValues") + .HasForeignKey("VertexAttributeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("VertexAttribute"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.DataGroup", b => + { + b.Navigation("EdgeEntity") + .IsRequired(); + + b.Navigation("VertexEntity") + .IsRequired(); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeAttribute", b => + { + b.Navigation("EdgeValues"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeEntity", b => + { + b.Navigation("EdgeAttributes"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.Role", b => + { + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.User", b => + { + b.Navigation("DataSets"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexAttribute", b => + { + b.Navigation("VertexValues"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexEntity", b => + { + b.Navigation("VertexAttributes"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/mohaymen-codestar-Team02/Migrations/20240820151916_InitialCreatec.cs b/mohaymen-codestar-Team02/Migrations/20240820151916_InitialCreatec.cs new file mode 100644 index 0000000..f8d1530 --- /dev/null +++ b/mohaymen-codestar-Team02/Migrations/20240820151916_InitialCreatec.cs @@ -0,0 +1,291 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace mohaymen_codestar_Team02.Migrations +{ + /// + public partial class InitialCreatec : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Roles", + columns: table => new + { + RoleId = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + RoleType = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Roles", x => x.RoleId); + }); + + migrationBuilder.CreateTable( + name: "Users", + columns: table => new + { + UserId = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Username = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + FirstName = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + LastName = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + Email = table.Column(type: "text", nullable: false), + Salt = table.Column(type: "bytea", maxLength: 256, nullable: false), + PasswordHash = table.Column(type: "bytea", maxLength: 256, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Users", x => x.UserId); + }); + + migrationBuilder.CreateTable( + name: "DataSets", + columns: table => new + { + DataGroupId = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Name = table.Column(type: "text", nullable: false), + CreateAt = table.Column(type: "timestamp with time zone", nullable: false), + UpdateAt = table.Column(type: "timestamp with time zone", nullable: false), + UserId = table.Column(type: "bigint", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_DataSets", x => x.DataGroupId); + table.ForeignKey( + name: "FK_DataSets_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "UserId", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "UserRoles", + columns: table => new + { + UserId = table.Column(type: "bigint", nullable: false), + RoleId = table.Column(type: "bigint", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_UserRoles", x => new { x.UserId, x.RoleId }); + table.ForeignKey( + name: "FK_UserRoles_Roles_RoleId", + column: x => x.RoleId, + principalTable: "Roles", + principalColumn: "RoleId", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_UserRoles_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "UserId", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "EdgeEntities", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Name = table.Column(type: "text", nullable: false), + DataGroupId = table.Column(type: "bigint", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_EdgeEntities", x => x.Id); + table.ForeignKey( + name: "FK_EdgeEntities_DataSets_DataGroupId", + column: x => x.DataGroupId, + principalTable: "DataSets", + principalColumn: "DataGroupId", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "VertexEntities", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Name = table.Column(type: "text", nullable: false), + DataGroupId = table.Column(type: "bigint", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_VertexEntities", x => x.Id); + table.ForeignKey( + name: "FK_VertexEntities_DataSets_DataGroupId", + column: x => x.DataGroupId, + principalTable: "DataSets", + principalColumn: "DataGroupId", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "EdgeAttributes", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Name = table.Column(type: "text", nullable: false), + EdgeEntityId = table.Column(type: "bigint", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_EdgeAttributes", x => x.Id); + table.ForeignKey( + name: "FK_EdgeAttributes_EdgeEntities_EdgeEntityId", + column: x => x.EdgeEntityId, + principalTable: "EdgeEntities", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "VertexAttributes", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + Name = table.Column(type: "text", nullable: false), + VertexEntityId = table.Column(type: "bigint", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_VertexAttributes", x => x.Id); + table.ForeignKey( + name: "FK_VertexAttributes_VertexEntities_VertexEntityId", + column: x => x.VertexEntityId, + principalTable: "VertexEntities", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "EdgeValues", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + StringValue = table.Column(type: "text", nullable: false), + EdgeAttributeId = table.Column(type: "bigint", nullable: false), + ObjectId = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_EdgeValues", x => x.Id); + table.ForeignKey( + name: "FK_EdgeValues_EdgeAttributes_EdgeAttributeId", + column: x => x.EdgeAttributeId, + principalTable: "EdgeAttributes", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "VertexValues", + columns: table => new + { + Id = table.Column(type: "bigint", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + StringValue = table.Column(type: "text", nullable: false), + VertexAttributeId = table.Column(type: "bigint", nullable: false), + ObjectId = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_VertexValues", x => x.Id); + table.ForeignKey( + name: "FK_VertexValues_VertexAttributes_VertexAttributeId", + column: x => x.VertexAttributeId, + principalTable: "VertexAttributes", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_DataSets_UserId", + table: "DataSets", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_EdgeAttributes_EdgeEntityId", + table: "EdgeAttributes", + column: "EdgeEntityId"); + + migrationBuilder.CreateIndex( + name: "IX_EdgeEntities_DataGroupId", + table: "EdgeEntities", + column: "DataGroupId", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_EdgeValues_EdgeAttributeId", + table: "EdgeValues", + column: "EdgeAttributeId"); + + migrationBuilder.CreateIndex( + name: "IX_UserRoles_RoleId", + table: "UserRoles", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "IX_VertexAttributes_VertexEntityId", + table: "VertexAttributes", + column: "VertexEntityId"); + + migrationBuilder.CreateIndex( + name: "IX_VertexEntities_DataGroupId", + table: "VertexEntities", + column: "DataGroupId", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_VertexValues_VertexAttributeId", + table: "VertexValues", + column: "VertexAttributeId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "EdgeValues"); + + migrationBuilder.DropTable( + name: "UserRoles"); + + migrationBuilder.DropTable( + name: "VertexValues"); + + migrationBuilder.DropTable( + name: "EdgeAttributes"); + + migrationBuilder.DropTable( + name: "Roles"); + + migrationBuilder.DropTable( + name: "VertexAttributes"); + + migrationBuilder.DropTable( + name: "EdgeEntities"); + + migrationBuilder.DropTable( + name: "VertexEntities"); + + migrationBuilder.DropTable( + name: "DataSets"); + + migrationBuilder.DropTable( + name: "Users"); + } + } +} diff --git a/mohaymen-codestar-Team02/Migrations/20240821134503_AddPermission.Designer.cs b/mohaymen-codestar-Team02/Migrations/20240821134503_AddPermission.Designer.cs new file mode 100644 index 0000000..c405ea6 --- /dev/null +++ b/mohaymen-codestar-Team02/Migrations/20240821134503_AddPermission.Designer.cs @@ -0,0 +1,418 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using mohaymen_codestar_Team02.Data; + +#nullable disable + +namespace mohaymen_codestar_Team02.Migrations +{ + [DbContext(typeof(DataContext))] + [Migration("20240821134503_AddPermission")] + partial class AddPermission + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.6") + .HasAnnotation("Proxies:ChangeTracking", false) + .HasAnnotation("Proxies:CheckEquality", false) + .HasAnnotation("Proxies:LazyLoading", true) + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.DataGroup", b => + { + b.Property("DataGroupId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("DataGroupId")); + + b.Property("CreateAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("bigint"); + + b.HasKey("DataGroupId"); + + b.HasIndex("UserId"); + + b.ToTable("DataSets"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeAttribute", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EdgeEntityId") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("EdgeEntityId"); + + b.ToTable("EdgeAttributes"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DataGroupId") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("DataGroupId") + .IsUnique(); + + b.ToTable("EdgeEntities"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeValue", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EdgeAttributeId") + .HasColumnType("bigint"); + + b.Property("ObjectId") + .IsRequired() + .HasColumnType("text"); + + b.Property("StringValue") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("EdgeAttributeId"); + + b.ToTable("EdgeValues"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.Role", b => + { + b.Property("RoleId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("RoleId")); + + b.Property("Permissions") + .IsRequired() + .HasColumnType("integer[]"); + + b.Property("RoleType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("RoleId"); + + b.ToTable("Roles"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.User", b => + { + b.Property("UserId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("UserId")); + + b.Property("Email") + .IsRequired() + .HasColumnType("text"); + + b.Property("FirstName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("LastName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PasswordHash") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("bytea"); + + b.Property("Salt") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("bytea"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("UserId"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.UserRole", b => + { + b.Property("UserId") + .HasColumnType("bigint"); + + b.Property("RoleId") + .HasColumnType("bigint"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("UserRoles"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexAttribute", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("VertexEntityId") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("VertexEntityId"); + + b.ToTable("VertexAttributes"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DataGroupId") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("DataGroupId") + .IsUnique(); + + b.ToTable("VertexEntities"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexValue", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ObjectId") + .IsRequired() + .HasColumnType("text"); + + b.Property("StringValue") + .IsRequired() + .HasColumnType("text"); + + b.Property("VertexAttributeId") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("VertexAttributeId"); + + b.ToTable("VertexValues"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.DataGroup", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.User", "User") + .WithMany("DataSets") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeAttribute", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeEntity", "EdgeEntity") + .WithMany("EdgeAttributes") + .HasForeignKey("EdgeEntityId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("EdgeEntity"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeEntity", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.DataGroup", "DataGroup") + .WithOne("EdgeEntity") + .HasForeignKey("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeEntity", "DataGroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DataGroup"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeValue", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeAttribute", "EdgeAttribute") + .WithMany("EdgeValues") + .HasForeignKey("EdgeAttributeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("EdgeAttribute"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.UserRole", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.Role", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("mohaymen_codestar_Team02.Models.User", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexAttribute", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.VertexEAV.VertexEntity", "VertexEntity") + .WithMany("VertexAttributes") + .HasForeignKey("VertexEntityId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("VertexEntity"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexEntity", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.DataGroup", "DataGroup") + .WithOne("VertexEntity") + .HasForeignKey("mohaymen_codestar_Team02.Models.VertexEAV.VertexEntity", "DataGroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DataGroup"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexValue", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.VertexEAV.VertexAttribute", "VertexAttribute") + .WithMany("VertexValues") + .HasForeignKey("VertexAttributeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("VertexAttribute"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.DataGroup", b => + { + b.Navigation("EdgeEntity") + .IsRequired(); + + b.Navigation("VertexEntity") + .IsRequired(); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeAttribute", b => + { + b.Navigation("EdgeValues"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeEntity", b => + { + b.Navigation("EdgeAttributes"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.Role", b => + { + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.User", b => + { + b.Navigation("DataSets"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexAttribute", b => + { + b.Navigation("VertexValues"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexEntity", b => + { + b.Navigation("VertexAttributes"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/mohaymen-codestar-Team02/Migrations/20240821134503_AddPermission.cs b/mohaymen-codestar-Team02/Migrations/20240821134503_AddPermission.cs new file mode 100644 index 0000000..35f293e --- /dev/null +++ b/mohaymen-codestar-Team02/Migrations/20240821134503_AddPermission.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace mohaymen_codestar_Team02.Migrations +{ + /// + public partial class AddPermission : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "Permissions", + table: "Roles", + type: "integer[]", + nullable: false, + defaultValue: new int[0]); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "Permissions", + table: "Roles"); + } + } +} diff --git a/mohaymen-codestar-Team02/Migrations/DataContextModelSnapshot.cs b/mohaymen-codestar-Team02/Migrations/DataContextModelSnapshot.cs new file mode 100644 index 0000000..8afc2cd --- /dev/null +++ b/mohaymen-codestar-Team02/Migrations/DataContextModelSnapshot.cs @@ -0,0 +1,415 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using mohaymen_codestar_Team02.Data; + +#nullable disable + +namespace mohaymen_codestar_Team02.Migrations +{ + [DbContext(typeof(DataContext))] + partial class DataContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.6") + .HasAnnotation("Proxies:ChangeTracking", false) + .HasAnnotation("Proxies:CheckEquality", false) + .HasAnnotation("Proxies:LazyLoading", true) + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.DataGroup", b => + { + b.Property("DataGroupId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("DataGroupId")); + + b.Property("CreateAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UpdateAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("bigint"); + + b.HasKey("DataGroupId"); + + b.HasIndex("UserId"); + + b.ToTable("DataSets"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeAttribute", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EdgeEntityId") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("EdgeEntityId"); + + b.ToTable("EdgeAttributes"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DataGroupId") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("DataGroupId") + .IsUnique(); + + b.ToTable("EdgeEntities"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeValue", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EdgeAttributeId") + .HasColumnType("bigint"); + + b.Property("ObjectId") + .IsRequired() + .HasColumnType("text"); + + b.Property("StringValue") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("EdgeAttributeId"); + + b.ToTable("EdgeValues"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.Role", b => + { + b.Property("RoleId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("RoleId")); + + b.Property("Permissions") + .IsRequired() + .HasColumnType("integer[]"); + + b.Property("RoleType") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("RoleId"); + + b.ToTable("Roles"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.User", b => + { + b.Property("UserId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("UserId")); + + b.Property("Email") + .IsRequired() + .HasColumnType("text"); + + b.Property("FirstName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("LastName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PasswordHash") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("bytea"); + + b.Property("Salt") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("bytea"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("UserId"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.UserRole", b => + { + b.Property("UserId") + .HasColumnType("bigint"); + + b.Property("RoleId") + .HasColumnType("bigint"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("UserRoles"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexAttribute", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("VertexEntityId") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("VertexEntityId"); + + b.ToTable("VertexAttributes"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DataGroupId") + .HasColumnType("bigint"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("DataGroupId") + .IsUnique(); + + b.ToTable("VertexEntities"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexValue", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ObjectId") + .IsRequired() + .HasColumnType("text"); + + b.Property("StringValue") + .IsRequired() + .HasColumnType("text"); + + b.Property("VertexAttributeId") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.HasIndex("VertexAttributeId"); + + b.ToTable("VertexValues"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.DataGroup", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.User", "User") + .WithMany("DataSets") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeAttribute", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeEntity", "EdgeEntity") + .WithMany("EdgeAttributes") + .HasForeignKey("EdgeEntityId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("EdgeEntity"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeEntity", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.DataGroup", "DataGroup") + .WithOne("EdgeEntity") + .HasForeignKey("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeEntity", "DataGroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DataGroup"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeValue", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeAttribute", "EdgeAttribute") + .WithMany("EdgeValues") + .HasForeignKey("EdgeAttributeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("EdgeAttribute"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.UserRole", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.Role", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("mohaymen_codestar_Team02.Models.User", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexAttribute", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.VertexEAV.VertexEntity", "VertexEntity") + .WithMany("VertexAttributes") + .HasForeignKey("VertexEntityId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("VertexEntity"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexEntity", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.DataGroup", "DataGroup") + .WithOne("VertexEntity") + .HasForeignKey("mohaymen_codestar_Team02.Models.VertexEAV.VertexEntity", "DataGroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("DataGroup"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexValue", b => + { + b.HasOne("mohaymen_codestar_Team02.Models.VertexEAV.VertexAttribute", "VertexAttribute") + .WithMany("VertexValues") + .HasForeignKey("VertexAttributeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("VertexAttribute"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.DataGroup", b => + { + b.Navigation("EdgeEntity") + .IsRequired(); + + b.Navigation("VertexEntity") + .IsRequired(); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeAttribute", b => + { + b.Navigation("EdgeValues"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.EdgeEAV.EdgeEntity", b => + { + b.Navigation("EdgeAttributes"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.Role", b => + { + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.User", b => + { + b.Navigation("DataSets"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexAttribute", b => + { + b.Navigation("VertexValues"); + }); + + modelBuilder.Entity("mohaymen_codestar_Team02.Models.VertexEAV.VertexEntity", b => + { + b.Navigation("VertexAttributes"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/mohaymen-codestar-Team02/Models/DataGroup.cs b/mohaymen-codestar-Team02/Models/DataGroup.cs index 169041b..bf6a0b4 100644 --- a/mohaymen-codestar-Team02/Models/DataGroup.cs +++ b/mohaymen-codestar-Team02/Models/DataGroup.cs @@ -13,6 +13,7 @@ public DataGroup(string name, long userId) Name = name; UserId = userId; } + [Key] public long DataGroupId { get; set; } public string Name { get; set; } diff --git a/mohaymen-codestar-Team02/Models/Edge.cs b/mohaymen-codestar-Team02/Models/Edge.cs new file mode 100644 index 0000000..406fcc5 --- /dev/null +++ b/mohaymen-codestar-Team02/Models/Edge.cs @@ -0,0 +1,10 @@ +using QuikGraph; + +namespace mohaymen_codestar_Team02.Models; + +public class Edge : IEdge +{ + public string Id { get; init; } + public string Source { get; init; } + public string Target { get; init; } +} \ No newline at end of file diff --git a/mohaymen-codestar-Team02/Models/EdgeEAV/EdgeAttribute.cs b/mohaymen-codestar-Team02/Models/EdgeEAV/EdgeAttribute.cs index af53cc9..1ae6a72 100644 --- a/mohaymen-codestar-Team02/Models/EdgeEAV/EdgeAttribute.cs +++ b/mohaymen-codestar-Team02/Models/EdgeEAV/EdgeAttribute.cs @@ -10,6 +10,7 @@ public EdgeAttribute(string name, long edgeEntityId) Name = name; EdgeEntityId = edgeEntityId; } + [Key] public long Id { get; set; } public string Name { get; set; } public long EdgeEntityId { get; set; } diff --git a/mohaymen-codestar-Team02/Models/EdgeEAV/EdgeEntity.cs b/mohaymen-codestar-Team02/Models/EdgeEAV/EdgeEntity.cs index 2409d03..80c4e93 100644 --- a/mohaymen-codestar-Team02/Models/EdgeEAV/EdgeEntity.cs +++ b/mohaymen-codestar-Team02/Models/EdgeEAV/EdgeEntity.cs @@ -8,8 +8,25 @@ public class EdgeEntity { public EdgeEntity(string name, long dataGroupId) { - _name = name + "!Edge" + "!" + Guid.NewGuid() + "!"; - DataGroupId = dataGroupId; + Regex regex = + new Regex( + "^[^!]+!Edge![0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}!$"); + var match = regex.Match(name); + if (match.Success) + { + _name = name; + DataGroupId = dataGroupId; + } + else if (!name.Contains("!")) + { + _name = name + "!Edge" + "!" + Guid.NewGuid() + "!"; + DataGroupId = dataGroupId; + } + else + { + throw new ArgumentException("your name contain !"); + } + } [Key] public long Id { get; set; } diff --git a/mohaymen-codestar-Team02/Models/EdgeEAV/EdgeValue.cs b/mohaymen-codestar-Team02/Models/EdgeEAV/EdgeValue.cs index 5caa070..f2037ce 100644 --- a/mohaymen-codestar-Team02/Models/EdgeEAV/EdgeValue.cs +++ b/mohaymen-codestar-Team02/Models/EdgeEAV/EdgeValue.cs @@ -11,6 +11,7 @@ public EdgeValue(string stringValue, long edgeAttributeId, string objectId) EdgeAttributeId = edgeAttributeId; ObjectId = objectId; } + [Key] public long Id { get; set; } public string StringValue { get; set; } public long EdgeAttributeId { get; set; } diff --git a/mohaymen-codestar-Team02/Models/Role.cs b/mohaymen-codestar-Team02/Models/Role.cs index e5ea52a..dc387a5 100644 --- a/mohaymen-codestar-Team02/Models/Role.cs +++ b/mohaymen-codestar-Team02/Models/Role.cs @@ -7,4 +7,5 @@ public class Role [Key] public long RoleId { get; set; } [Required] public string RoleType { get; set; } = string.Empty; public virtual ICollection UserRoles { get; set; } = new List(); + public virtual List Permissions { get; set; } = new List(); } \ No newline at end of file diff --git a/mohaymen-codestar-Team02/Models/Vertex.cs b/mohaymen-codestar-Team02/Models/Vertex.cs new file mode 100644 index 0000000..10b30e2 --- /dev/null +++ b/mohaymen-codestar-Team02/Models/Vertex.cs @@ -0,0 +1,7 @@ +namespace mohaymen_codestar_Team02.Models; + +public class Vertex +{ + public string Id { get; init; } + public string Value { get; init; } +} \ No newline at end of file diff --git a/mohaymen-codestar-Team02/Models/VertexEAV/VertexAttribute.cs b/mohaymen-codestar-Team02/Models/VertexEAV/VertexAttribute.cs index f814d90..f2cef12 100644 --- a/mohaymen-codestar-Team02/Models/VertexEAV/VertexAttribute.cs +++ b/mohaymen-codestar-Team02/Models/VertexEAV/VertexAttribute.cs @@ -11,6 +11,7 @@ public VertexAttribute(string name, long vertexEntityId) Name = name; VertexEntityId = vertexEntityId; } + [Key] public long Id { get; set; } public string Name { get; set; } public long VertexEntityId { get; set; } diff --git a/mohaymen-codestar-Team02/Models/VertexEAV/VertexEntity.cs b/mohaymen-codestar-Team02/Models/VertexEAV/VertexEntity.cs index 39e731b..8c9b459 100644 --- a/mohaymen-codestar-Team02/Models/VertexEAV/VertexEntity.cs +++ b/mohaymen-codestar-Team02/Models/VertexEAV/VertexEntity.cs @@ -9,7 +9,16 @@ public class VertexEntity { public VertexEntity(string name, long dataGroupId) { - if (!name.Contains("!")) + var regex = + new Regex( + "^[^!]+!vertex![0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}!$"); + var match = regex.Match(name); + if (match.Success) + { + _name = name; + DataGroupId = dataGroupId; + } + else if (!name.Contains("!")) { _name = name + "!vertex" + "!" + Guid.NewGuid() + "!"; DataGroupId = dataGroupId; diff --git a/mohaymen-codestar-Team02/Models/VertexEAV/VertexValue.cs b/mohaymen-codestar-Team02/Models/VertexEAV/VertexValue.cs index 0aad88e..18bc7cf 100644 --- a/mohaymen-codestar-Team02/Models/VertexEAV/VertexValue.cs +++ b/mohaymen-codestar-Team02/Models/VertexEAV/VertexValue.cs @@ -6,13 +6,13 @@ namespace mohaymen_codestar_Team02.Models.VertexEAV; public class VertexValue { - public VertexValue(string stringValue, long vertexAttributeId, string objectId) { StringValue = stringValue; VertexAttributeId = vertexAttributeId; ObjectId = objectId; } + [Key] public long Id { get; set; } public string StringValue { get; set; } diff --git a/mohaymen-codestar-Team02/Models/permission.cs b/mohaymen-codestar-Team02/Models/permission.cs new file mode 100644 index 0000000..a5bc76d --- /dev/null +++ b/mohaymen-codestar-Team02/Models/permission.cs @@ -0,0 +1,27 @@ +namespace mohaymen_codestar_Team02.Models; + +public enum Permission +{ + AddRole = 1, + DeleteRole = 2, + UserRegister = 3, + DeleteUser = 4, + GetUserList = 5, + GetSingleUser = 6, + GetRoleList = 7, + Login = 8, + Logout = 9, + ChangePass = 10, + UpdateInfo = 11, + SeeAllGraphData = 12, + SeeSingleGraphData = 13, + GetInfoOfVertex = 14, + GetInfoOfEdge = 15, + AddGraphData = 16, + DeleteGraphData = 17, + DeleteVertex = 18, + DeleteEdge = 19, + DeleteGraphDataFromDatabase = 20, + DeleteVertexFromDatabase = 21, + DeleteEdgeFromDatabase = 22 +} \ No newline at end of file diff --git a/mohaymen-codestar-Team02/Program.cs b/mohaymen-codestar-Team02/Program.cs index ca14881..c9d1f8c 100644 --- a/mohaymen-codestar-Team02/Program.cs +++ b/mohaymen-codestar-Team02/Program.cs @@ -2,17 +2,18 @@ using mohaymen_codestar_Team02.initialProgram; var builder = WebApplication.CreateBuilder(args); -ConfigureEnvironment(); - +builder.Configuration + .AddJsonFile("appsettings.json") + .AddEnvironmentVariables(); builder.Services.AddCors(options => { options.AddPolicy("AllowSpecificOrigins", builder => { builder.WithOrigins("http://localhost:4200") - .AllowAnyHeader() - .AllowAnyMethod() - .AllowCredentials(); + .AllowAnyHeader() + .AllowAnyMethod() + .AllowCredentials(); }); }); @@ -24,9 +25,4 @@ app.UseCors("AllowSpecificOrigins"); -app.Run(); - -void ConfigureEnvironment() -{ - Env.Load(); -} \ No newline at end of file +app.Run(); \ No newline at end of file diff --git a/mohaymen-codestar-Team02/Services/Administration/AdminService.cs b/mohaymen-codestar-Team02/Services/Administration/AdminService.cs index b43ddd4..6349632 100644 --- a/mohaymen-codestar-Team02/Services/Administration/AdminService.cs +++ b/mohaymen-codestar-Team02/Services/Administration/AdminService.cs @@ -46,7 +46,7 @@ public AdminService(DataContext context, ICookieService cookieService, ITokenSer if (user is null) return new ServiceResponse(null, ApiResponseType.NotFound, Resources.UserNotFoundMessage); - GetUserDto userDto = _mapper.Map(user); + var userDto = _mapper.Map(user); return new ServiceResponse(userDto, ApiResponseType.Success, Resources.UserRetrievedMassage); } @@ -83,9 +83,7 @@ public async Task>> GetAllRoles() { var token = _cookieService.GetCookieValue(); if (string.IsNullOrEmpty(token)) - { return new ServiceResponse(null, ApiResponseType.Unauthorized, Resources.UnauthorizedMessage); - } var adminUsername = _tokenService.GetUserNameFromToken(); var admin = await GetUser(adminUsername); @@ -105,7 +103,7 @@ public async Task>> GetAllRoles() await _context.Users.AddAsync(user); await _context.SaveChangesAsync(); - GetUserDto userDto = _mapper.Map(user); + var userDto = _mapper.Map(user); return new ServiceResponse(userDto, ApiResponseType.Created, Resources.UserCreatedSuccessfullyMessage); @@ -135,7 +133,7 @@ public async Task>> GetAllRoles() _context.Users.Remove(foundUser); await _context.SaveChangesAsync(); - GetUserDto userDto = _mapper.Map(user); + var userDto = _mapper.Map(user); return new ServiceResponse(userDto, ApiResponseType.Success, Resources.UserDeletionSuccessful); } @@ -176,7 +174,7 @@ public async Task>> GetAllRoles() await _context.UserRoles.AddAsync(userRole); await _context.SaveChangesAsync(); - GetUserDto userDto = _mapper.Map(user); + var userDto = _mapper.Map(user); return new ServiceResponse(userDto, ApiResponseType.Success, Resources.RoleAddedSuccessfulyMassage); @@ -212,15 +210,17 @@ public async Task>> GetAllRoles() _context.UserRoles.Remove(userRole); await _context.SaveChangesAsync(); - GetUserDto userDto = _mapper.Map(user); + var userDto = _mapper.Map(user); return new ServiceResponse(userDto, ApiResponseType.Success, Resources.RoleRemovedSuccessfullyMessage); } - private async Task GetUser(string? username) => - await _context.Users.FirstOrDefaultAsync(x => + private async Task GetUser(string? username) + { + return await _context.Users.FirstOrDefaultAsync(x => username != null && x.Username != null && x.Username.ToLower().Equals(username.ToLower())); + } private Task IsAdmin(User? user) { @@ -238,12 +238,16 @@ private Task IsAdmin(User? user) return await _context.Roles.FirstOrDefaultAsync(x => x.RoleType.ToLower() == roleType.ToLower()); } - private async Task GetUserRole(Role foundRole, User foundUser) => - await _context.UserRoles.FirstOrDefaultAsync(x => + private async Task GetUserRole(Role foundRole, User foundUser) + { + return await _context.UserRoles.FirstOrDefaultAsync(x => x.User.Username != null && foundUser.Username != null && x.RoleId == foundRole.RoleId && x.User.Username.ToLower() == foundUser.Username.ToLower()); + } - private async Task UserExists(string? username) => - await _context.Users.AnyAsync(x => + private async Task UserExists(string? username) + { + return await _context.Users.AnyAsync(x => username != null && x.Username != null && x.Username.ToLower() == username.ToLower()); + } } \ No newline at end of file diff --git a/mohaymen-codestar-Team02/Services/Authenticatoin/AuthenticationService.cs b/mohaymen-codestar-Team02/Services/Authenticatoin/AuthenticationService.cs index 4ddb425..e5883ad 100644 --- a/mohaymen-codestar-Team02/Services/Authenticatoin/AuthenticationService.cs +++ b/mohaymen-codestar-Team02/Services/Authenticatoin/AuthenticationService.cs @@ -30,9 +30,7 @@ public AuthenticationService(DataContext context, ICookieService cookieService, public async Task> Login(string username, string password) { if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) - { return new ServiceResponse(null, ApiResponseType.BadRequest, Resources.InvalidInpute); - } var user = await GetUser(username); @@ -49,23 +47,22 @@ public AuthenticationService(DataContext context, ICookieService cookieService, _cookieService.CreateCookie(_tokenService.CreateToken(claims)); - GetUserDto userDto = _mapper.Map(user); + var userDto = _mapper.Map(user); return new ServiceResponse(userDto, ApiResponseType.Success, Resources.LoginSuccessfulMessage); } public ServiceResponse Logout() { - if (_cookieService.GetCookieValue() != null) - { - _cookieService.GetExpiredCookie(); - } + if (_cookieService.GetCookieValue() != null) _cookieService.GetExpiredCookie(); return new ServiceResponse(null, ApiResponseType.Success, Resources.LogoutSuccessfuly); } - private async Task GetUser(string username) => - await _context.Users.FirstOrDefaultAsync(x => + private async Task GetUser(string username) + { + return await _context.Users.FirstOrDefaultAsync(x => x.Username != null && x.Username.ToLower().Equals(username.ToLower())); + } } \ No newline at end of file diff --git a/mohaymen-codestar-Team02/Services/DataAdminService/DataAdminService.cs b/mohaymen-codestar-Team02/Services/DataAdminService/DataAdminService.cs index af0820a..fc9936d 100644 --- a/mohaymen-codestar-Team02/Services/DataAdminService/DataAdminService.cs +++ b/mohaymen-codestar-Team02/Services/DataAdminService/DataAdminService.cs @@ -1,4 +1,6 @@ +using mohaymen_codestar_Team02.Dto.GraphDTO; using mohaymen_codestar_Team02.Models; +using mohaymen_codestar_Team02.Models.EdgeEAV; using mohaymen_codestar_Team02.Services.StoreData.Abstraction; namespace mohaymen_codestar_Team02.Services.DataAdminService; @@ -7,43 +9,84 @@ public class DataAdminService : IDataAdminService { private readonly IStorHandler storHandler; - public DataAdminService(IStorHandler storHandler) + private readonly IDisplayDataService _displayDataService; + public DataAdminService(IStorHandler storHandler, IDisplayDataService displayDataService) { this.storHandler = storHandler; + _displayDataService = displayDataService; } + public async Task> StoreData(string? edgeFile, string? vertexFile, string graphName , string? edgeEntityName, string vertexEntityName, string userName) { - if (string.IsNullOrEmpty(edgeEntityName) || string.IsNullOrEmpty(graphName) || - string.IsNullOrEmpty(vertexEntityName)) - return new ServiceResponse(string.Empty, ApiResponseType.BadRequest, Data.Resources.InvalidInpute); + try + { + if (string.IsNullOrEmpty(edgeEntityName) || string.IsNullOrEmpty(graphName) || + string.IsNullOrEmpty(vertexEntityName)) + return new ServiceResponse(string.Empty, ApiResponseType.BadRequest, + Data.Resources.InvalidInpute); - var dataGroupId = await storHandler.StoreDataSet(graphName, userName); - if (dataGroupId == -1) - return new ServiceResponse(string.Empty, ApiResponseType.BadRequest, Data.Resources.InvalidInpute); + var dataGroupId = await storHandler.StoreDataSet(graphName, userName); + if (dataGroupId == -1) + return new ServiceResponse(string.Empty, ApiResponseType.BadRequest, + Data.Resources.InvalidInpute); - if (!await storHandler.EdageStorer.StoreFileData(edgeEntityName, edgeFile, dataGroupId)) - return new ServiceResponse(string.Empty, - ApiResponseType.BadRequest, Data.Resources.InvalidInpute); + if (!await storHandler.EdageStorer.StoreFileData(edgeEntityName, edgeFile, dataGroupId)) + return new ServiceResponse(string.Empty, + ApiResponseType.BadRequest, Data.Resources.InvalidInpute); - if (!await storHandler.VertexStorer.StoreFileData(vertexEntityName, vertexFile, dataGroupId)) - return new ServiceResponse(string.Empty, - ApiResponseType.BadRequest, Data.Resources.InvalidInpute); + if (!await storHandler.VertexStorer.StoreFileData(vertexEntityName, vertexFile, dataGroupId)) + return new ServiceResponse(string.Empty, + ApiResponseType.BadRequest, Data.Resources.InvalidInpute); - return new ServiceResponse(null, ApiResponseType.Success, string.Empty); + return new ServiceResponse(null, ApiResponseType.Success, string.Empty); + } + catch (NullReferenceException e) + { + return new ServiceResponse(null, ApiResponseType.NotFound, e.Message); + } } - public Task> DisplayDataSet() + public Task> DisplayDataSetAsGraph(string dataSetName, string vertexFieldName, string sourceField, string targetField) { throw new NotImplementedException(); } - public Task> DisplayVertexData() + public Task> DisplayGraph() + { + throw new NotImplementedException(); + } + + public Task> DisplayDataSet() { throw new NotImplementedException(); } - public Task> DisplayEdgeData() + /* + public Task> DisplayGraph(string databaseName, string sourceEdgeIdentifierFieldName, + string destinationEdgeIdentifierFieldName, string vertexIdentifierFieldName) + { + var graph = _displayDataService.GetGraph2(databaseName, sourceEdgeIdentifierFieldName, destinationEdgeIdentifierFieldName, + vertexIdentifierFieldName); + return new Task>() + } +*/ + + public async Task> DisplayGeraphData(string databaseName, string sourceEdgeIdentifierFieldName, + string destinationEdgeIdentifierFieldName, string vertexIdentifierFieldName) + { + var graph = _displayDataService.GetGraph(databaseName, sourceEdgeIdentifierFieldName, destinationEdgeIdentifierFieldName, + vertexIdentifierFieldName); + + var dto = new DisplayGraphDto() + { + Vertices = graph.vertices, + Edges = graph.edges, + }; + return new ServiceResponse(dto, ApiResponseType.Success, ""); + } + + public Task>> DisplayEdgeData() { throw new NotImplementedException(); } diff --git a/mohaymen-codestar-Team02/Services/DataAdminService/IDataAdminService.cs b/mohaymen-codestar-Team02/Services/DataAdminService/IDataAdminService.cs index 234e7f5..d3e9175 100644 --- a/mohaymen-codestar-Team02/Services/DataAdminService/IDataAdminService.cs +++ b/mohaymen-codestar-Team02/Services/DataAdminService/IDataAdminService.cs @@ -1,3 +1,4 @@ +using mohaymen_codestar_Team02.Dto.GraphDTO; using mohaymen_codestar_Team02.Models; namespace mohaymen_codestar_Team02.Services.DataAdminService; @@ -8,6 +9,7 @@ Task> StoreData(string? edgeFile, string? vertexFile, st , string? edgeEntityName, string vertexEntityName, string userName); Task> DisplayDataSet(); - Task> DisplayVertexData(); - Task> DisplayEdgeData(); + + Task> DisplayGeraphData(string databaseName, string sourceEdgeIdentifierFieldName, + string destinationEdgeIdentifierFieldName, string vertexIdentifierFieldName); } \ No newline at end of file diff --git a/mohaymen-codestar-Team02/Services/DisplayData/DisplayService.cs b/mohaymen-codestar-Team02/Services/DisplayData/DisplayService.cs index 000b080..8caa7c0 100644 --- a/mohaymen-codestar-Team02/Services/DisplayData/DisplayService.cs +++ b/mohaymen-codestar-Team02/Services/DisplayData/DisplayService.cs @@ -1,23 +1,107 @@ using Microsoft.EntityFrameworkCore; using mohaymen_codestar_Team02.Data; +using mohaymen_codestar_Team02.Models; +using mohaymen_codestar_Team02.Services.DynamicService; using mohaymen_codestar_Team02.Services.TokenService; using QuikGraph; namespace mohaymen_codestar_Team02.Services; -public class DisplayService +public class DisplayService : IDisplayDataService { private readonly DataContext _context; - private readonly ModelBuilder _modelBuilder; - private readonly ObjectBuilder _objectBuilder; - public DisplayService(DataContext context, ModelBuilder modelBuilder, ObjectBuilder objectBuilder) + public DisplayService(DataContext context) { _context = context; - _modelBuilder = modelBuilder; - _objectBuilder = objectBuilder; } + public (List vertices, List edges) GetGraph(string databaseName, string sourceEdgeIdentifierFieldName, + string destinationEdgeIdentifierFieldName, string vertexIdentifierFieldName) + { + var dataSet = _context.DataSets.Include(ds => ds.VertexEntity) + .ThenInclude(ve => ve.VertexAttributes).ThenInclude(vv => vv.VertexValues).Include(ds => ds.EdgeEntity) + .ThenInclude(ee => ee.EdgeAttributes).ThenInclude(ev => ev.EdgeValues).FirstOrDefault(ds => ds.Name.ToLower().Equals(databaseName.ToLower())); + + var vertexRecords = dataSet.VertexEntity.VertexAttributes.Select(a => a.VertexValues).SelectMany(v => v) + .GroupBy(v => v.ObjectId); + + List vertices = new List(); + foreach (var record in vertexRecords) + { + var value = record.SingleOrDefault(r => r.VertexAttribute.Name == vertexIdentifierFieldName).StringValue; + Vertex v = new Vertex() + { + Id = record.Key, + Value = value + }; + vertices.Add(v); + } + + var edgeRecords = dataSet.EdgeEntity.EdgeAttributes.Select(ea => ea.EdgeValues).SelectMany(v => v) + .GroupBy(v => v.ObjectId); + + List edges = new List(); + foreach (var record in edgeRecords) + { + string sourceValue = string.Empty; + string destinationValue = string.Empty; + foreach (var item in record) + { + if (item.EdgeAttribute.Name == sourceEdgeIdentifierFieldName) + { + sourceValue = item.StringValue; + } + if (item.EdgeAttribute.Name == destinationEdgeIdentifierFieldName) + { + destinationValue = item.StringValue; + } + } + + List sources = new List(); + List destinations = new List(); + + foreach (var record1 in vertexRecords) + { + foreach (var item in record1) + { + if (item.VertexAttribute.Name == vertexIdentifierFieldName && item.StringValue == sourceValue) + { + Vertex vertex = new Vertex() + { + Id = record1.Key + }; + sources.Add(vertex); + } + if (item.VertexAttribute.Name == vertexIdentifierFieldName && item.StringValue == destinationValue) + { + Vertex vertex = new Vertex() + { + Id = record1.Key + }; + destinations.Add(vertex); + } + } + } + foreach (var source in sources) + { + foreach (var des in destinations) + { + Edge edge = new Edge() + { + Id = record.Key, + Source = source.Id, + Target = des.Id + }; + edges.Add(edge); + } + } + } + + return (vertices, edges); + } + + /* public void GetGraph(string databaseName, string sourceEdgeIdentifierFieldName, string destinationEdgeIdentifierFieldName, string vertexIdentifierFieldName, bool directed, out List vertices, List edges) @@ -109,5 +193,5 @@ public void GetGraph(string databaseName, string sourceEdgeIdentifierFieldName, } } } - } + }*/ } \ No newline at end of file diff --git a/mohaymen-codestar-Team02/Services/DisplayData/IDisplayDataService.cs b/mohaymen-codestar-Team02/Services/DisplayData/IDisplayDataService.cs index e6f3388..bc9c43e 100644 --- a/mohaymen-codestar-Team02/Services/DisplayData/IDisplayDataService.cs +++ b/mohaymen-codestar-Team02/Services/DisplayData/IDisplayDataService.cs @@ -4,7 +4,7 @@ namespace mohaymen_codestar_Team02.Services; public interface IDisplayDataService { - ServiceResponse DisplayGraph(); - ServiceResponse DisplayVertex(); - ServiceResponse DisplayEdge(); + (List vertices, List edges) GetGraph(string databaseName, + string sourceEdgeIdentifierFieldName, + string destinationEdgeIdentifierFieldName, string vertexIdentifierFieldName); } \ No newline at end of file diff --git a/mohaymen-codestar-Team02/Services/DynamicService/IModelBuilder.cs b/mohaymen-codestar-Team02/Services/DynamicService/IModelBuilder.cs new file mode 100644 index 0000000..180aac8 --- /dev/null +++ b/mohaymen-codestar-Team02/Services/DynamicService/IModelBuilder.cs @@ -0,0 +1,8 @@ +using System.Reflection.Emit; + +namespace mohaymen_codestar_Team02.Services.DynamicService; + +public interface IModelBuilder +{ + public Type CreateDynamicClass(string className, Dictionary fieldNamesTypes, Type interfaceType); +} \ No newline at end of file diff --git a/mohaymen-codestar-Team02/Services/DynamicService/IObjectBuilder.cs b/mohaymen-codestar-Team02/Services/DynamicService/IObjectBuilder.cs new file mode 100644 index 0000000..396024b --- /dev/null +++ b/mohaymen-codestar-Team02/Services/DynamicService/IObjectBuilder.cs @@ -0,0 +1,6 @@ +namespace mohaymen_codestar_Team02.Services.DynamicService; + +public interface IObjectBuilder +{ + public object CreateDynamicObject(Type objectType, Dictionary attributeValues); +} \ No newline at end of file diff --git a/mohaymen-codestar-Team02/Services/ModelBuilder.cs b/mohaymen-codestar-Team02/Services/DynamicService/ModelBuilderr.cs similarity index 71% rename from mohaymen-codestar-Team02/Services/ModelBuilder.cs rename to mohaymen-codestar-Team02/Services/DynamicService/ModelBuilderr.cs index 4c984d6..6e47269 100644 --- a/mohaymen-codestar-Team02/Services/ModelBuilder.cs +++ b/mohaymen-codestar-Team02/Services/DynamicService/ModelBuilderr.cs @@ -1,23 +1,19 @@ using System.Reflection; using System.Reflection.Emit; +using mohaymen_codestar_Team02.Services.DynamicService; -namespace mohaymen_codestar_Team02.Services; +namespace mohaymen_codestar_Team02.Services.DynamicService; -public class ModelBuilder +public class ModelBuilderr : IModelBuilder { public Type CreateDynamicClass(string className, Dictionary fieldNamesTypes, Type interfaceType) { var typeBuilder = GetTypeBuilder(className); - if (interfaceType != null) - { - typeBuilder.AddInterfaceImplementation(interfaceType); - } + if (interfaceType != null) typeBuilder.AddInterfaceImplementation(interfaceType); foreach (var fieldNamesType in fieldNamesTypes) - { CreateProperty(typeBuilder, fieldNamesType.Key, fieldNamesType.Value); - } return typeBuilder.CreateType(); } @@ -35,15 +31,20 @@ private void CreateProperty(TypeBuilder typeBuilder, string propertyName, Type p { var fieldBuilder = typeBuilder.DefineField("_" + propertyName, propertyType, FieldAttributes.Private); - var propertyBuilder = typeBuilder.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null); - var getPropMthdBldr = typeBuilder.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, Type.EmptyTypes); + var propertyBuilder = + typeBuilder.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null); + var getPropMthdBldr = typeBuilder.DefineMethod("get_" + propertyName, + MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, + Type.EmptyTypes); var getIl = getPropMthdBldr.GetILGenerator(); getIl.Emit(OpCodes.Ldarg_0); getIl.Emit(OpCodes.Ldfld, fieldBuilder); getIl.Emit(OpCodes.Ret); - var setPropMthdBldr = typeBuilder.DefineMethod("set_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, null, new[] { propertyType }); + var setPropMthdBldr = typeBuilder.DefineMethod("set_" + propertyName, + MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, null, + new[] { propertyType }); var setIl = setPropMthdBldr.GetILGenerator(); setIl.Emit(OpCodes.Ldarg_0); diff --git a/mohaymen-codestar-Team02/Services/ObjectBuilder.cs b/mohaymen-codestar-Team02/Services/DynamicService/ObjectBuilder.cs similarity index 77% rename from mohaymen-codestar-Team02/Services/ObjectBuilder.cs rename to mohaymen-codestar-Team02/Services/DynamicService/ObjectBuilder.cs index 2beb875..a1a2d5f 100644 --- a/mohaymen-codestar-Team02/Services/ObjectBuilder.cs +++ b/mohaymen-codestar-Team02/Services/DynamicService/ObjectBuilder.cs @@ -1,23 +1,19 @@ -using mohaymen_codestar_Team02.Data; +namespace mohaymen_codestar_Team02.Services.DynamicService; -namespace mohaymen_codestar_Team02.Services.TokenService; - -public class ObjectBuilder +public class ObjectBuilder : IObjectBuilder { - public object CreateDynamicObject(Type objectType, Dictionary attributeValues) { var dynamicObject = Activator.CreateInstance(objectType); foreach (var attributeValue in attributeValues) - { objectType.GetProperty(attributeValue.Key).SetValue(dynamicObject, attributeValue.Value); - } return dynamicObject; } - public object CreateDynamicObject1(Type objectType, Dictionary attributeValues, Type vertexType, object source, object destination) + public object CreateDynamicObject1(Type objectType, Dictionary attributeValues, Type vertexType, + object source, object destination) { var dynamicObject = Activator.CreateInstance(objectType); @@ -25,9 +21,7 @@ public object CreateDynamicObject1(Type objectType, Dictionary a vertexType.GetProperty("Target").SetValue(vertexType, destination); foreach (var attributeValue in attributeValues) - { objectType.GetProperty(attributeValue.Key).SetValue(dynamicObject, attributeValue.Value); - } return dynamicObject; } diff --git a/mohaymen-codestar-Team02/Services/FileReaderService/ReadCsvFile.cs b/mohaymen-codestar-Team02/Services/FileReaderService/ReadCsvFile.cs index 0a09edd..e3a518c 100644 --- a/mohaymen-codestar-Team02/Services/FileReaderService/ReadCsvFile.cs +++ b/mohaymen-codestar-Team02/Services/FileReaderService/ReadCsvFile.cs @@ -4,7 +4,10 @@ public class ReadCsvFile : IFileReader { public string Read(IFormFile? file) { - if (file == null || file.Length == 0) return ""; + if (file == null || file.Length == 0) throw new FormatException(); + var supportedTypes = new[] { "csv" }; + var fileExt = Path.GetExtension(file.FileName).Substring(1); + if (!supportedTypes.Contains(fileExt.ToLower())) throw new FormatException(); using (var reader = new StreamReader(file.OpenReadStream())) { diff --git a/mohaymen-codestar-Team02/Services/ProfileService/ProfileService.cs b/mohaymen-codestar-Team02/Services/ProfileService/ProfileService.cs index 0041bd7..404d2c3 100644 --- a/mohaymen-codestar-Team02/Services/ProfileService/ProfileService.cs +++ b/mohaymen-codestar-Team02/Services/ProfileService/ProfileService.cs @@ -31,9 +31,7 @@ public async Task> ChangePassword(string previousPasswor { var token = _cookieService.GetCookieValue(); if (string.IsNullOrEmpty(token)) - { return new ServiceResponse(new { }, ApiResponseType.Unauthorized, Resources.UnauthorizedMessage); - } var username = _tokenService.GetUserNameFromToken(); var user = await GetUser(username); @@ -51,7 +49,8 @@ public async Task> ChangePassword(string previousPasswor _context.Users.Update(user); await _context.SaveChangesAsync(); - return new ServiceResponse(new { }, ApiResponseType.Success, Resources.PasswordChangedSuccessfulyMessage); + return new ServiceResponse(new { }, ApiResponseType.Success, + Resources.PasswordChangedSuccessfulyMessage); } public async Task> UpdateUser(UpdateUserDto updateUserDto) @@ -60,9 +59,7 @@ public async Task> ChangePassword(string previousPasswor var token = _cookieService.GetCookieValue(); if (string.IsNullOrEmpty(token)) - { return new ServiceResponse(null, ApiResponseType.Unauthorized, Resources.UnauthorizedMessage); - } var username = _tokenService.GetUserNameFromToken(); var user = await GetUser(username); @@ -81,6 +78,8 @@ public async Task> ChangePassword(string previousPasswor Resources.ProfileInfoUpdateSuccessfulyMessage); } - private Task GetUser(string? username) => - _context.Users.FirstOrDefaultAsync(x => x.Username.ToLower() == username.ToLower()); + private Task GetUser(string? username) + { + return _context.Users.FirstOrDefaultAsync(x => x.Username.ToLower() == username.ToLower()); + } } \ No newline at end of file diff --git a/mohaymen-codestar-Team02/Services/StoreData/EdgeStorerCsv.cs b/mohaymen-codestar-Team02/Services/StoreData/EdgeStorerCsv.cs index 3861653..79f202a 100644 --- a/mohaymen-codestar-Team02/Services/StoreData/EdgeStorerCsv.cs +++ b/mohaymen-codestar-Team02/Services/StoreData/EdgeStorerCsv.cs @@ -8,10 +8,12 @@ namespace mohaymen_codestar_Team02.Services.StoreData; public class EdgeStorerCsv : IEdageStorer { private readonly IServiceProvider? _serviceProvider; + public EdgeStorerCsv(IServiceProvider? serviceProvider) { _serviceProvider = serviceProvider; } + public async Task StoreFileData(string entityName, string dataFile, long dataGroupId) { using var scope = _serviceProvider.CreateScope(); @@ -28,7 +30,12 @@ public async Task StoreFileData(string entityName, string dataFile, long d var headerLine = reader.ReadLine(); if (headerLine == null) return false; - var headers = headerLine.Split(','); + var headers = headerLine.Split("\",\""); + headers[0] = headers[0].Substring(1); + var lastWodrd = headers[headers.Length - 1]; + headers[headers.Length - 1] = lastWodrd.Substring(0, lastWodrd.Length - 1); + + foreach (var att in headers) edgeAttributes.Add(new EdgeAttribute(att, edgeEntity.Id)); foreach (var attribute in edgeAttributes) await dataContext.EdgeAttributes.AddAsync(attribute); diff --git a/mohaymen-codestar-Team02/Services/StoreData/StoreDataService.cs b/mohaymen-codestar-Team02/Services/StoreData/StoreDataService.cs index a79dcd2..cd2cbea 100644 --- a/mohaymen-codestar-Team02/Services/StoreData/StoreDataService.cs +++ b/mohaymen-codestar-Team02/Services/StoreData/StoreDataService.cs @@ -15,6 +15,7 @@ public StoreDataService(IServiceProvider serviceProvider, IEdageStorer edageStor VertexStorer = vertexStorer; EdageStorer = edageStorer; } + public IEdageStorer EdageStorer { get; set; } public IVertexStorer VertexStorer { get; set; } @@ -25,8 +26,9 @@ public async Task StoreDataSet(string? nameData, string userName) try { if (string.IsNullOrEmpty(nameData)) return -1; - var setData = new DataGroup(nameData, - context.Users.SingleOrDefault(u => u.Username.ToLower() == userName.ToLower()).UserId); + var user = context.Users.SingleOrDefault(u => u.Username.ToLower() == userName.ToLower()); + if (user == null) throw new NullReferenceException(Resources.UserNotFoundMessage); + var setData = new DataGroup(nameData, user.UserId); await context.DataSets.AddAsync(setData); await context.SaveChangesAsync(); return setData.DataGroupId; diff --git a/mohaymen-codestar-Team02/Services/StoreData/VertexStorerCsv.cs b/mohaymen-codestar-Team02/Services/StoreData/VertexStorerCsv.cs index e841525..e5a705f 100644 --- a/mohaymen-codestar-Team02/Services/StoreData/VertexStorerCsv.cs +++ b/mohaymen-codestar-Team02/Services/StoreData/VertexStorerCsv.cs @@ -8,10 +8,12 @@ namespace mohaymen_codestar_Team02.Services.StoreData; public class VertexStorerCsv : IVertexStorer { private readonly IServiceProvider _serviceProvider; + public VertexStorerCsv(IServiceProvider serviceProvider) { - this._serviceProvider = serviceProvider; + _serviceProvider = serviceProvider; } + public async Task StoreFileData(string entityName, string dataFile, long dataGroupId) { using var scope = _serviceProvider.CreateScope(); diff --git a/mohaymen-codestar-Team02/initialProgram/InitialServices.cs b/mohaymen-codestar-Team02/initialProgram/InitialServices.cs index 7c518f8..8e7d04f 100644 --- a/mohaymen-codestar-Team02/initialProgram/InitialServices.cs +++ b/mohaymen-codestar-Team02/initialProgram/InitialServices.cs @@ -10,6 +10,7 @@ using mohaymen_codestar_Team02.Services.Authenticatoin; using mohaymen_codestar_Team02.Services.CookieService; using mohaymen_codestar_Team02.Services.DataAdminService; +using mohaymen_codestar_Team02.Services.DynamicService; using mohaymen_codestar_Team02.Services.FileReaderService; using mohaymen_codestar_Team02.Services.PasswordHandller; using mohaymen_codestar_Team02.Services.ProfileService; @@ -38,7 +39,7 @@ public static void ConfigureServices(IServiceCollection services, WebApplication services.AddHttpContextAccessor(); // Configure DbContext and Dependency Injection - var cs = Environment.GetEnvironmentVariable("CONNECTION_STRING"); + var cs = builder.Configuration["CONNECTION_STRING"]; services.AddDbContext(options => options.UseNpgsql(cs)); @@ -50,11 +51,14 @@ public static void ConfigureServices(IServiceCollection services, WebApplication .AddScoped() .AddScoped() .AddScoped() - .AddSingleton() - .AddSingleton() - .AddTransient() - .AddSingleton() - .AddSingleton(); + .AddScoped() + .AddScoped() + .AddScoped() + .AddScoped() + .AddScoped() + .AddScoped() + .AddScoped() + .AddScoped(); services.AddAutoMapper(typeof(AutoMapperProfile)); services.AddAuthorization(); @@ -99,20 +103,76 @@ public void SeadRole() { List roles = new() { - new() + new Role { RoleId = 1, - RoleType = "SystemAdmin" + RoleType = "SystemAdmin", + Permissions = new List() + { + Permission.AddRole, Permission.DeleteRole, + Permission.UserRegister, + Permission.DeleteUser, + Permission.GetUserList, + Permission.GetSingleUser, + Permission.GetRoleList, + Permission.Login, + Permission.Logout, + Permission.ChangePass, + Permission.UpdateInfo, + Permission.SeeAllGraphData, + Permission.SeeSingleGraphData, + Permission.GetInfoOfVertex, + Permission.GetInfoOfEdge, + Permission.AddGraphData, + Permission.DeleteGraphData, + Permission.DeleteVertex, + Permission.DeleteEdge, + Permission.DeleteGraphDataFromDatabase, + Permission.DeleteVertexFromDatabase, + Permission.DeleteEdgeFromDatabase + } }, - new() + new Role { RoleId = 2, - RoleType = "Analyst" + RoleType = "Analyst", Permissions = new List() + { + Permission.Login, + Permission.Logout, + Permission.ChangePass, + Permission.UpdateInfo, + Permission.SeeAllGraphData, + Permission.SeeSingleGraphData, + Permission.GetInfoOfVertex, + Permission.GetInfoOfEdge, + Permission.DeleteGraphData, + Permission.DeleteVertex, + Permission.DeleteGraphData, + Permission.DeleteVertex, + Permission.DeleteEdge + } }, - new() + new Role { RoleId = 3, - RoleType = "DataAdmin" + RoleType = "DataAdmin", Permissions = new List() + { + Permission.Login, + Permission.Logout, + Permission.ChangePass, + Permission.UpdateInfo, + Permission.SeeAllGraphData, + Permission.SeeSingleGraphData, + Permission.GetInfoOfVertex, + Permission.GetInfoOfEdge, + Permission.AddGraphData, + Permission.DeleteGraphData, + Permission.DeleteVertex, + Permission.DeleteEdge, + Permission.DeleteGraphDataFromDatabase, + Permission.DeleteVertexFromDatabase, + Permission.DeleteEdgeFromDatabase + } } }; @@ -141,7 +201,7 @@ public void SeadAdmin() var role = _context.Roles.FirstOrDefault(r => r.RoleType.ToLower().Equals(RoleType.SystemAdmin.ToString().ToLower())); - UserRole userRole = new UserRole() + var userRole = new UserRole() { RoleId = role.RoleId, UserId = admin.UserId, Role = role, User = admin }; _context.UserRoles.Add(userRole); diff --git a/mohaymen-codestar-Team02_XUnitTest/Servies/Administration/AdminServiceTest.cs b/mohaymen-codestar-Team02_XUnitTest/Servies/Administration/AdminServiceTest.cs index 99665b3..6d884f1 100644 --- a/mohaymen-codestar-Team02_XUnitTest/Servies/Administration/AdminServiceTest.cs +++ b/mohaymen-codestar-Team02_XUnitTest/Servies/Administration/AdminServiceTest.cs @@ -29,7 +29,7 @@ public AdminServiceTest() _mapper = Substitute.For(); var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()) + .UseInMemoryDatabase(Guid.NewGuid().ToString()) .Options; _mockContext = new DataContext(options); _sut = new AdminService(_mockContext, _cookieService, _tokenService, _passwordService, _mapper); @@ -96,8 +96,8 @@ public async Task Register_ShouldReturnCreated_WhenUserIsSuccessfullyRegistered( // Arrange FixTheReturnOfCookies("admin"); var newUser = AddUserWithRole("admin", "SystemAdmin", 1); - byte[] fakePasswordHash = new byte[] { 1, 2, 3, 4 }; - byte[] fakePasswordSalt = new byte[] { 5, 6, 7, 8 }; + var fakePasswordHash = new byte[] { 1, 2, 3, 4 }; + var fakePasswordSalt = new byte[] { 5, 6, 7, 8 }; _passwordService .When(x => x.CreatePasswordHash(Arg.Any(), out Arg.Any(), out Arg.Any())) @@ -123,8 +123,8 @@ public async Task Register_ShouldSetCorrectPasswordHashAndSalt_WhenUserIsSuccess FixTheReturnOfCookies("admin"); AddUserWithRole("admin", "SystemAdmin", 1); - byte[] fakePasswordHash = new byte[] { 1, 2, 3, 4 }; - byte[] fakePasswordSalt = new byte[] { 5, 6, 7, 8 }; + var fakePasswordHash = new byte[] { 1, 2, 3, 4 }; + var fakePasswordSalt = new byte[] { 5, 6, 7, 8 }; _passwordService .When(x => x.CreatePasswordHash(Arg.Any(), out Arg.Any(), out Arg.Any())) @@ -480,5 +480,4 @@ public async Task DeleteRole_ShouldReturnYouCanNotDeleteYourself_WhenAdminDelete // Assert Assert.Equal(ApiResponseType.BadRequest, result.Type); } - } \ No newline at end of file diff --git a/mohaymen-codestar-Team02_XUnitTest/Servies/Authenticatoin/AuthenticationService.cs b/mohaymen-codestar-Team02_XUnitTest/Servies/Authenticatoin/AuthenticationService.cs index 695e78c..e7d04d4 100644 --- a/mohaymen-codestar-Team02_XUnitTest/Servies/Authenticatoin/AuthenticationService.cs +++ b/mohaymen-codestar-Team02_XUnitTest/Servies/Authenticatoin/AuthenticationService.cs @@ -31,7 +31,7 @@ public AuthenticationServiceTests() var mapper = config.CreateMapper(); var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(databaseName: "TestDatabase") + .UseInMemoryDatabase("TestDatabase") .Options; _mockContext = new DataContext(options); _sut = new AuthenticationService(_mockContext, _cookieService, _tokenService, _passwordService, mapper); @@ -43,7 +43,7 @@ public AuthenticationServiceTests() public async Task Login_ShouldReturnBadRequest_WhenUserIsNullOrEmpty(string username) { // Arrange - string password = "password123"; + var password = "password123"; // Act var result = await _sut.Login(username, password); @@ -57,7 +57,7 @@ public async Task Login_ShouldReturnBadRequest_WhenUserIsNullOrEmpty(string user public async Task Login_ShouldReturnBadRequest_WhenPasswordIsNullOrEmpty(string password) { // Arrange - string username = "username123"; + var username = "username123"; // Act var result = await _sut.Login(username, password); @@ -70,8 +70,8 @@ public async Task Login_ShouldReturnBadRequest_WhenPasswordIsNullOrEmpty(string public async Task Login_ShouldReturnBadRequest_WhenUserDoesNotExist() { // Arrange - string username = "nonexistentUser"; - string password = "password123"; + var username = "nonexistentUser"; + var password = "password123"; // Act var result = await _sut.Login(username, password); @@ -85,8 +85,8 @@ public async Task Login_ShouldReturnBadRequest_WhenUserDoesNotExist() public async Task Login_ShouldReturnBadRequest_WhenPasswordIsIncorrect() { // Arrange - string username = "existingUser"; - string password = "wrongPassword"; + var username = "existingUser"; + var password = "wrongPassword"; AddUserToDatabase(username, "correctPassword"); _passwordService.VerifyPasswordHash(password, Arg.Any(), Arg.Any()) @@ -104,14 +104,14 @@ public async Task Login_ShouldReturnBadRequest_WhenPasswordIsIncorrect() public async Task Login_ShouldReturnSuccess_WhenCredentialsAreCorrect() { // Arrange - string username = "existingUser"; - string password = "correctPassword"; + var username = "existingUser"; + var password = "correctPassword"; AddUserToDatabase(username, password); _passwordService.VerifyPasswordHash(password, Arg.Any(), Arg.Any()) .Returns(true); - string fakeToken = "fakeToken"; + var fakeToken = "fakeToken"; _tokenService.CreateToken(Arg.Any()).Returns(fakeToken); // Act @@ -128,7 +128,7 @@ private void AddUserToDatabase(string username, string password) { Username = username, Salt = new byte[128], - PasswordHash = new byte[64], + PasswordHash = new byte[64] }; using (var hmac = new System.Security.Cryptography.HMACSHA512(user.Salt)) { diff --git a/mohaymen-codestar-Team02_XUnitTest/Servies/CookieService/CookieServiceTest.cs b/mohaymen-codestar-Team02_XUnitTest/Servies/CookieService/CookieServiceTest.cs index 03d2a81..59a2171 100644 --- a/mohaymen-codestar-Team02_XUnitTest/Servies/CookieService/CookieServiceTest.cs +++ b/mohaymen-codestar-Team02_XUnitTest/Servies/CookieService/CookieServiceTest.cs @@ -1,113 +1,112 @@ using Microsoft.AspNetCore.Http; using NSubstitute; -namespace mohaymen_codestar_Team02_XUnitTest.Servies.CookieService +namespace mohaymen_codestar_Team02_XUnitTest.Servies.CookieService; + +public class CookieServiceTests { - public class CookieServiceTests + private readonly IHttpContextAccessor _httpContextAccessor; + private readonly mohaymen_codestar_Team02.Services.CookieService.CookieService _sut; + + public CookieServiceTests() + { + _httpContextAccessor = Substitute.For(); + _sut = new mohaymen_codestar_Team02.Services.CookieService.CookieService(_httpContextAccessor); + } + + [Fact] + public void CreateCookie_ShouldAddCookieToResponse_WhenCreateCookieIsCalled() + { + // Arrange + var responseCookies = Substitute.For(); + var httpResponse = Substitute.For(); + httpResponse.Cookies.Returns(responseCookies); + + var httpContext = Substitute.For(); + httpContext.Response.Returns(httpResponse); + + _httpContextAccessor.HttpContext.Returns(httpContext); + var cookieValue = "test_cookie_value"; + + // Act + _sut.CreateCookie(cookieValue); + + // Assert + responseCookies.Received(1).Append( + "login", + cookieValue, + Arg.Is(options => + options.HttpOnly && options.Secure && options.SameSite == SameSiteMode.Strict) + ); + } + + [Fact] + public void GetCookieValue_ShouldReturnCookieValue_WhenCookieExists() + { + // Arrange + var requestCookies = Substitute.For(); + requestCookies["login"].Returns("test_cookie_value"); + + var httpRequest = Substitute.For(); + httpRequest.Cookies.Returns(requestCookies); + + var httpContext = Substitute.For(); + httpContext.Request.Returns(httpRequest); + + _httpContextAccessor.HttpContext.Returns(httpContext); + + // Act + var result = _sut.GetCookieValue(); + + // Assert + Assert.Equal("test_cookie_value", result); + } + + [Fact] + public void GetCookieValue_ShouldReturnNull_WhenCookieDoesNotExist() + { + // Arrange + var requestCookies = Substitute.For(); + var httpRequest = Substitute.For(); + httpRequest.Cookies.Returns(requestCookies); + + var httpContext = Substitute.For(); + httpContext.Request.Returns(httpRequest); + + _httpContextAccessor.HttpContext.Returns(httpContext); + + // Act + var result = _sut.GetCookieValue(); + + // Assert + Assert.Equal(string.Empty, result); + } + + [Fact] + public void GetExpiredCookie_ShouldReturnExpiredCookie_WhenGetExpiredCookieIsCalled() { - private readonly IHttpContextAccessor _httpContextAccessor; - private readonly mohaymen_codestar_Team02.Services.CookieService.CookieService _sut; - - public CookieServiceTests() - { - _httpContextAccessor = Substitute.For(); - _sut = new mohaymen_codestar_Team02.Services.CookieService.CookieService(_httpContextAccessor); - } - - [Fact] - public void CreateCookie_ShouldAddCookieToResponse_WhenCreateCookieIsCalled() - { - // Arrange - var responseCookies = Substitute.For(); - var httpResponse = Substitute.For(); - httpResponse.Cookies.Returns(responseCookies); - - var httpContext = Substitute.For(); - httpContext.Response.Returns(httpResponse); - - _httpContextAccessor.HttpContext.Returns(httpContext); - string cookieValue = "test_cookie_value"; - - // Act - _sut.CreateCookie(cookieValue); - - // Assert - responseCookies.Received(1).Append( - "login", - cookieValue, - Arg.Is(options => - options.HttpOnly && options.Secure && options.SameSite == SameSiteMode.Strict) - ); - } - - [Fact] - public void GetCookieValue_ShouldReturnCookieValue_WhenCookieExists() - { - // Arrange - var requestCookies = Substitute.For(); - requestCookies["login"].Returns("test_cookie_value"); - - var httpRequest = Substitute.For(); - httpRequest.Cookies.Returns(requestCookies); - - var httpContext = Substitute.For(); - httpContext.Request.Returns(httpRequest); - - _httpContextAccessor.HttpContext.Returns(httpContext); - - // Act - var result = _sut.GetCookieValue(); - - // Assert - Assert.Equal("test_cookie_value", result); - } - - [Fact] - public void GetCookieValue_ShouldReturnNull_WhenCookieDoesNotExist() - { - // Arrange - var requestCookies = Substitute.For(); - var httpRequest = Substitute.For(); - httpRequest.Cookies.Returns(requestCookies); - - var httpContext = Substitute.For(); - httpContext.Request.Returns(httpRequest); - - _httpContextAccessor.HttpContext.Returns(httpContext); - - // Act - var result = _sut.GetCookieValue(); - - // Assert - Assert.Equal(string.Empty, result); - } - - [Fact] - public void GetExpiredCookie_ShouldReturnExpiredCookie_WhenGetExpiredCookieIsCalled() - { - // Arrange - var responseCookies = Substitute.For(); - var httpResponse = Substitute.For(); - httpResponse.Cookies.Returns(responseCookies); - - var httpContext = Substitute.For(); - httpContext.Response.Returns(httpResponse); - - _httpContextAccessor.HttpContext.Returns(httpContext); - - // Act - _sut.GetExpiredCookie(); - - // Assert - responseCookies.Received(1).Append( - "login", - "", - Arg.Is(options => - options.HttpOnly && - options.Secure && - options.Expires.HasValue && - options.Expires.Value < DateTime.Now) - ); - } + // Arrange + var responseCookies = Substitute.For(); + var httpResponse = Substitute.For(); + httpResponse.Cookies.Returns(responseCookies); + + var httpContext = Substitute.For(); + httpContext.Response.Returns(httpResponse); + + _httpContextAccessor.HttpContext.Returns(httpContext); + + // Act + _sut.GetExpiredCookie(); + + // Assert + responseCookies.Received(1).Append( + "login", + "", + Arg.Is(options => + options.HttpOnly && + options.Secure && + options.Expires.HasValue && + options.Expires.Value < DateTime.Now) + ); } } \ No newline at end of file diff --git a/mohaymen-codestar-Team02_XUnitTest/Servies/DataAdminService/DataAdminServiceTest.cs b/mohaymen-codestar-Team02_XUnitTest/Servies/DataAdminService/DataAdminServiceTest.cs index d38f886..c07ee82 100644 --- a/mohaymen-codestar-Team02_XUnitTest/Servies/DataAdminService/DataAdminServiceTest.cs +++ b/mohaymen-codestar-Team02_XUnitTest/Servies/DataAdminService/DataAdminServiceTest.cs @@ -1,4 +1,5 @@ using mohaymen_codestar_Team02.Models; +using mohaymen_codestar_Team02.Services; using mohaymen_codestar_Team02.Services.StoreData.Abstraction; using NSubstitute; @@ -7,12 +8,15 @@ namespace mohaymen_codestar_Team02_XUnitTest.Servies.DataAdminService; public class DataAdminServiceTest { private readonly IStorHandler _storHandler; + private readonly IDisplayDataService _displayDataService; private readonly mohaymen_codestar_Team02.Services.DataAdminService.DataAdminService _sut; public DataAdminServiceTest() { _storHandler = Substitute.For(); - _sut = new mohaymen_codestar_Team02.Services.DataAdminService.DataAdminService(_storHandler); + _displayDataService = Substitute.For(); + _sut = new mohaymen_codestar_Team02.Services.DataAdminService.DataAdminService(_storHandler, + _displayDataService); _storHandler.EdageStorer.StoreFileData(Arg.Any(), Arg.Any(), Arg.Any()).Returns(true); _storHandler.VertexStorer.StoreFileData(Arg.Any(), Arg.Any(), Arg.Any()).Returns(true); } @@ -28,6 +32,7 @@ public async Task StoreData_ReturnsBadRequest_WhenNameIsNullOrEmpty(string? name //Assert Assert.Equal(ApiResponseType.BadRequest, result.Type); } + [Fact] public async Task StoreData_ReturnsBadRequest_WhenCreatingTheDataGroupIsFail() { diff --git a/mohaymen-codestar-Team02_XUnitTest/Servies/PasswordHandler/PasswordHandlerTest.cs b/mohaymen-codestar-Team02_XUnitTest/Servies/PasswordHandler/PasswordHandlerTest.cs index 0e022ea..b3ffd52 100644 --- a/mohaymen-codestar-Team02_XUnitTest/Servies/PasswordHandler/PasswordHandlerTest.cs +++ b/mohaymen-codestar-Team02_XUnitTest/Servies/PasswordHandler/PasswordHandlerTest.cs @@ -15,12 +15,12 @@ public PasswordServiceTests() public void CreatePasswordHash_ShouldGenerateDifferentHashAndSalt_ForDifferentPasswords() { // Arrange - string password1 = "password1"; - string password2 = "password2"; + var password1 = "password1"; + var password2 = "password2"; // Act - _sut.CreatePasswordHash(password1, out byte[] hash1, out byte[] salt1); - _sut.CreatePasswordHash(password2, out byte[] hash2, out byte[] salt2); + _sut.CreatePasswordHash(password1, out var hash1, out var salt1); + _sut.CreatePasswordHash(password2, out var hash2, out var salt2); // Assert Assert.NotEqual(hash1, hash2); @@ -31,11 +31,11 @@ public void CreatePasswordHash_ShouldGenerateDifferentHashAndSalt_ForDifferentPa public void CreatePasswordHash_ShouldGenerateSameHash_ForSamePasswordAndSalt() { // Arrange - string password = "password"; + var password = "password"; // Act - _sut.CreatePasswordHash(password, out byte[] hash1, out byte[] salt); - _sut.CreatePasswordHash(password, out byte[] hash2, out _); + _sut.CreatePasswordHash(password, out var hash1, out var salt); + _sut.CreatePasswordHash(password, out var hash2, out _); // Assert Assert.NotEqual(hash1, hash2); // چون برای هر بار فراخوانی salt جدید تولید می‌شود. @@ -45,11 +45,11 @@ public void CreatePasswordHash_ShouldGenerateSameHash_ForSamePasswordAndSalt() public void VerifyPasswordHash_ShouldReturnTrue_ForValidPassword() { // Arrange - string password = "password"; - _sut.CreatePasswordHash(password, out byte[] hash, out byte[] salt); + var password = "password"; + _sut.CreatePasswordHash(password, out var hash, out var salt); // Act - bool isValid = _sut.VerifyPasswordHash(password, hash, salt); + var isValid = _sut.VerifyPasswordHash(password, hash, salt); // Assert Assert.True(isValid); @@ -59,14 +59,14 @@ public void VerifyPasswordHash_ShouldReturnTrue_ForValidPassword() public void VerifyPasswordHash_ShouldReturnFalse_ForInvalidPassword() { // Arrange - string correctPassword = "password"; - string wrongPassword = "wrongpassword"; - _sut.CreatePasswordHash(correctPassword, out byte[] hash, out byte[] salt); + var correctPassword = "password"; + var wrongPassword = "wrongpassword"; + _sut.CreatePasswordHash(correctPassword, out var hash, out var salt); // Act - bool isValid = _sut.VerifyPasswordHash(wrongPassword, hash, salt); + var isValid = _sut.VerifyPasswordHash(wrongPassword, hash, salt); // Assert Assert.False(isValid); } -} +} \ No newline at end of file diff --git a/mohaymen-codestar-Team02_XUnitTest/Servies/ProfileService/ProfileServiceTest.cs b/mohaymen-codestar-Team02_XUnitTest/Servies/ProfileService/ProfileServiceTest.cs index 5a62073..c099d80 100644 --- a/mohaymen-codestar-Team02_XUnitTest/Servies/ProfileService/ProfileServiceTest.cs +++ b/mohaymen-codestar-Team02_XUnitTest/Servies/ProfileService/ProfileServiceTest.cs @@ -9,173 +9,172 @@ using mohaymen_codestar_Team02.Services.PasswordHandller; using NSubstitute; -namespace mohaymen_codestar_Team02_XUnitTest.Servies.ProfileService +namespace mohaymen_codestar_Team02_XUnitTest.Servies.ProfileService; + +public class ProfileServiceTests { - public class ProfileServiceTests + private readonly mohaymen_codestar_Team02.Services.ProfileService.ProfileService _sut; + private readonly ICookieService _cookieService; + private readonly DataContext _mockContext; + private readonly IPasswordService _passwordService; + private readonly ITokenService _tokenService; + private readonly IMapper _mapper; + + public ProfileServiceTests() { - private readonly mohaymen_codestar_Team02.Services.ProfileService.ProfileService _sut; - private readonly ICookieService _cookieService; - private readonly DataContext _mockContext; - private readonly IPasswordService _passwordService; - private readonly ITokenService _tokenService; - private readonly IMapper _mapper; - - public ProfileServiceTests() - { - _passwordService = Substitute.For(); - _cookieService = Substitute.For(); - _tokenService = Substitute.For(); - - var config = new MapperConfiguration(cfg => - { - cfg.CreateMap(); - cfg.CreateMap(); - }); - _mapper = config.CreateMapper(); + _passwordService = Substitute.For(); + _cookieService = Substitute.For(); + _tokenService = Substitute.For(); - var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(databaseName: "TestDatabase") - .Options; - _mockContext = new DataContext(options); + var config = new MapperConfiguration(cfg => + { + cfg.CreateMap(); + cfg.CreateMap(); + }); + _mapper = config.CreateMapper(); + + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase("TestDatabase") + .Options; + _mockContext = new DataContext(options); + + _sut = new mohaymen_codestar_Team02.Services.ProfileService.ProfileService(_mockContext, _cookieService, + _passwordService, _tokenService, _mapper); + } - _sut = new mohaymen_codestar_Team02.Services.ProfileService.ProfileService(_mockContext, _cookieService, - _passwordService, _tokenService, _mapper); - } + [Fact] + public async Task ChangePassword_ShouldReturnUnauthorized_WhenCookieIsEmpty() + { + // Arrange + _cookieService.GetCookieValue().Returns((string)null); - [Fact] - public async Task ChangePassword_ShouldReturnUnauthorized_WhenCookieIsEmpty() - { - // Arrange - _cookieService.GetCookieValue().Returns((string)null); + // Act + var result = await _sut.ChangePassword("oldPassword", "newPassword"); - // Act - var result = await _sut.ChangePassword("oldPassword", "newPassword"); + // Assert + Assert.Equal(ApiResponseType.Unauthorized, result.Type); + } - // Assert - Assert.Equal(ApiResponseType.Unauthorized, result.Type); - } + [Fact] + public async Task ChangePassword_ShouldReturnBadRequest_WhenUserNotFound() + { + // Arrange + _cookieService.GetCookieValue().Returns("validToken"); + _tokenService.GetUserNameFromToken().Returns("nonexistentUser"); - [Fact] - public async Task ChangePassword_ShouldReturnBadRequest_WhenUserNotFound() - { - // Arrange - _cookieService.GetCookieValue().Returns("validToken"); - _tokenService.GetUserNameFromToken().Returns("nonexistentUser"); + // Act + var result = await _sut.ChangePassword("oldPassword", "newPassword"); - // Act - var result = await _sut.ChangePassword("oldPassword", "newPassword"); + // Assert + Assert.Equal(ApiResponseType.BadRequest, result.Type); + } - // Assert - Assert.Equal(ApiResponseType.BadRequest, result.Type); - } + [Fact] + public async Task ChangePassword_ShouldReturnBadRequest_WhenWrongPassword() + { + // Arrange + var user = AddUserToDatabase("existingUser", "oldPassword"); + _cookieService.GetCookieValue().Returns("validToken"); + _tokenService.GetUserNameFromToken().Returns("existingUser"); + _passwordService.VerifyPasswordHash("newPassword", user.PasswordHash, user.Salt).Returns(false); - [Fact] - public async Task ChangePassword_ShouldReturnBadRequest_WhenWrongPassword() - { - // Arrange - var user = AddUserToDatabase("existingUser", "oldPassword"); - _cookieService.GetCookieValue().Returns("validToken"); - _tokenService.GetUserNameFromToken().Returns("existingUser"); - _passwordService.VerifyPasswordHash("newPassword", user.PasswordHash, user.Salt).Returns(false); + // Act + var result = await _sut.ChangePassword("oldPassword", "newPassword"); - // Act - var result = await _sut.ChangePassword("oldPassword", "newPassword"); + // Assert + Assert.Equal(ApiResponseType.BadRequest, result.Type); + } - // Assert - Assert.Equal(ApiResponseType.BadRequest, result.Type); - } + [Fact] + public async Task ChangePassword_ShouldReturnSuccess_WhenPasswordIsChanged() + { + // Arrange + var user = AddUserToDatabase("existingUser", "oldPassword"); + _cookieService.GetCookieValue().Returns("validToken"); + _tokenService.GetUserNameFromToken().Returns("existingUser"); + _passwordService.VerifyPasswordHash(Arg.Any(), Arg.Any(), Arg.Any()).Returns(true); + var fakePasswordHash = new byte[] { 1, 2, 3, 4 }; + var fakePasswordSalt = new byte[] { 5, 6, 7, 8 }; + + _passwordService + .When(x => x.CreatePasswordHash(Arg.Any(), out Arg.Any(), out Arg.Any())) + .Do(x => + { + x[1] = fakePasswordHash; + x[2] = fakePasswordSalt; + }); + // Act + var result = await _sut.ChangePassword("oldPassword", "newPassword"); - [Fact] - public async Task ChangePassword_ShouldReturnSuccess_WhenPasswordIsChanged() - { - // Arrange - var user = AddUserToDatabase("existingUser", "oldPassword"); - _cookieService.GetCookieValue().Returns("validToken"); - _tokenService.GetUserNameFromToken().Returns("existingUser"); - _passwordService.VerifyPasswordHash(Arg.Any(), Arg.Any(), Arg.Any()).Returns(true); - byte[] fakePasswordHash = new byte[] { 1, 2, 3, 4 }; - byte[] fakePasswordSalt = new byte[] { 5, 6, 7, 8 }; - - _passwordService - .When(x => x.CreatePasswordHash(Arg.Any(), out Arg.Any(), out Arg.Any())) - .Do(x => - { - x[1] = fakePasswordHash; - x[2] = fakePasswordSalt; - }); - // Act - var result = await _sut.ChangePassword("oldPassword", "newPassword"); - - // Assert - Assert.Equal(ApiResponseType.Success, result.Type); - } + // Assert + Assert.Equal(ApiResponseType.Success, result.Type); + } - [Fact] - public async Task UpdateUser_ShouldReturnUnauthorized_WhenCookieIsEmpty() - { - // Arrange - var updateUserDto = new UpdateUserDto - { FirstName = "NewFirstName", LastName = "NewLastName", Email = "newemail@example.com" }; - _cookieService.GetCookieValue().Returns(string.Empty); + [Fact] + public async Task UpdateUser_ShouldReturnUnauthorized_WhenCookieIsEmpty() + { + // Arrange + var updateUserDto = new UpdateUserDto + { FirstName = "NewFirstName", LastName = "NewLastName", Email = "newemail@example.com" }; + _cookieService.GetCookieValue().Returns(string.Empty); - // Act - var result = await _sut.UpdateUser(updateUserDto); + // Act + var result = await _sut.UpdateUser(updateUserDto); - // Assert - Assert.Equal(ApiResponseType.Unauthorized, result.Type); - } + // Assert + Assert.Equal(ApiResponseType.Unauthorized, result.Type); + } - [Fact] - public async Task UpdateUser_ShouldReturnBadRequest_WhenUserNotFound() - { - // Arrange - var updateUserDto = new UpdateUserDto - { FirstName = "NewFirstName", LastName = "NewLastName", Email = "newemail@example.com" }; - _cookieService.GetCookieValue().Returns("validToken"); - _tokenService.GetUserNameFromToken().Returns("nonexistentUser"); + [Fact] + public async Task UpdateUser_ShouldReturnBadRequest_WhenUserNotFound() + { + // Arrange + var updateUserDto = new UpdateUserDto + { FirstName = "NewFirstName", LastName = "NewLastName", Email = "newemail@example.com" }; + _cookieService.GetCookieValue().Returns("validToken"); + _tokenService.GetUserNameFromToken().Returns("nonexistentUser"); - // Act - var result = await _sut.UpdateUser(updateUserDto); + // Act + var result = await _sut.UpdateUser(updateUserDto); - // Assert - Assert.Equal(ApiResponseType.BadRequest, result.Type); - } + // Assert + Assert.Equal(ApiResponseType.BadRequest, result.Type); + } - [Fact] - public async Task UpdateUser_ShouldReturnSuccess_WhenUserIsUpdated() - { - // Arrange - var user = AddUserToDatabase("existingUser", "password"); - _cookieService.GetCookieValue().Returns("validToken"); - _tokenService.GetUserNameFromToken().Returns("existingUser"); + [Fact] + public async Task UpdateUser_ShouldReturnSuccess_WhenUserIsUpdated() + { + // Arrange + var user = AddUserToDatabase("existingUser", "password"); + _cookieService.GetCookieValue().Returns("validToken"); + _tokenService.GetUserNameFromToken().Returns("existingUser"); - var updateUserDto = new UpdateUserDto - { FirstName = "NewFirstName", LastName = "NewLastName", Email = "newemail@example.com" }; + var updateUserDto = new UpdateUserDto + { FirstName = "NewFirstName", LastName = "NewLastName", Email = "newemail@example.com" }; - // Act - var result = await _sut.UpdateUser(updateUserDto); + // Act + var result = await _sut.UpdateUser(updateUserDto); - // Assert - Assert.Equal(ApiResponseType.Success, result.Type); - } + // Assert + Assert.Equal(ApiResponseType.Success, result.Type); + } - private User AddUserToDatabase(string username, string password) + private User AddUserToDatabase(string username, string password) + { + var user = new User { - var user = new User - { - Username = username, - Salt = new byte[128], - PasswordHash = new byte[64], - }; - - using (var hmac = new System.Security.Cryptography.HMACSHA512(user.Salt)) - { - user.PasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password)); - } + Username = username, + Salt = new byte[128], + PasswordHash = new byte[64] + }; - _mockContext.Users.Add(user); - _mockContext.SaveChanges(); - return user; + using (var hmac = new System.Security.Cryptography.HMACSHA512(user.Salt)) + { + user.PasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password)); } + + _mockContext.Users.Add(user); + _mockContext.SaveChanges(); + return user; } } \ No newline at end of file diff --git a/mohaymen-codestar-Team02_XUnitTest/Servies/StorData/EdgeStorerCsvTest.cs b/mohaymen-codestar-Team02_XUnitTest/Servies/StorData/EdgeStorerCsvTest.cs index 5a2554f..6a55d50 100644 --- a/mohaymen-codestar-Team02_XUnitTest/Servies/StorData/EdgeStorerCsvTest.cs +++ b/mohaymen-codestar-Team02_XUnitTest/Servies/StorData/EdgeStorerCsvTest.cs @@ -5,70 +5,69 @@ using mohaymen_codestar_Team02.Services.StoreData; using NSubstitute; -namespace mohaymen_codestar_Team02_XUnitTest.Servies.StorData +namespace mohaymen_codestar_Team02_XUnitTest.Servies.StorData; + +public class EdgeStorerCsvTests { - public class EdgeStorerCsvTests - { - private EdgeStorerCsv _sut; - private DataContext _dataContext; - private ServiceProvider _serviceProvider; + private EdgeStorerCsv _sut; + private DataContext _dataContext; + private ServiceProvider _serviceProvider; - public EdgeStorerCsvTests() - { - var serviceCollection = new ServiceCollection(); + public EdgeStorerCsvTests() + { + var serviceCollection = new ServiceCollection(); - var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()) - .Options; + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; - serviceCollection.AddScoped(_ => new DataContext(options)); + serviceCollection.AddScoped(_ => new DataContext(options)); - _serviceProvider = serviceCollection.BuildServiceProvider(); + _serviceProvider = serviceCollection.BuildServiceProvider(); - _sut = new(_serviceProvider); - using var scope = _serviceProvider.CreateScope(); - _dataContext = scope.ServiceProvider.GetRequiredService(); - } + _sut = new EdgeStorerCsv(_serviceProvider); + using var scope = _serviceProvider.CreateScope(); + _dataContext = scope.ServiceProvider.GetRequiredService(); + } - [Fact] - public async Task StoreFileData_ShouldReturnTrue_WhenDataIsValid() - { - using var scope = _serviceProvider.CreateScope(); - _dataContext = scope.ServiceProvider.GetRequiredService(); + [Fact] + public async Task StoreFileData_ShouldReturnTrue_WhenDataIsValid() + { + using var scope = _serviceProvider.CreateScope(); + _dataContext = scope.ServiceProvider.GetRequiredService(); - // Arrange - string entityName = "TestEntity"; - string dataFile = "attribute1,attribute2\nvalue1,value2\nlol1,lol2"; - var dataGroupId = 1; + // Arrange + var entityName = "TestEntity"; + var dataFile = "attribute1,attribute2\nvalue1,value2\nlol1,lol2"; + var dataGroupId = 1; - // Act - var result = await _sut.StoreFileData(entityName, dataFile, dataGroupId); + // Act + var result = await _sut.StoreFileData(entityName, dataFile, dataGroupId); - // Assert - Assert.True(result); - Assert.Equal(1, await _dataContext.EdgeEntities.CountAsync()); - Assert.Equal(2, await _dataContext.EdgeAttributes.CountAsync()); - Assert.Equal(2, await _dataContext.EdgeValues.CountAsync()); - } + // Assert + Assert.True(result); + Assert.Equal(1, await _dataContext.EdgeEntities.CountAsync()); + Assert.Equal(1, await _dataContext.EdgeAttributes.CountAsync()); + Assert.Equal(2, await _dataContext.EdgeValues.CountAsync()); + } - [Fact] - public async Task StoreFileData_ShouldReturnFalse_WhenHeaderLineIsNull() - { - using var scope = _serviceProvider.CreateScope(); - _dataContext = scope.ServiceProvider.GetRequiredService(); - // Arrange - string entityName = "TestEntity"; - string dataFile = ""; // No headers in the file - var dataGroupId = 1; + [Fact] + public async Task StoreFileData_ShouldReturnFalse_WhenHeaderLineIsNull() + { + using var scope = _serviceProvider.CreateScope(); + _dataContext = scope.ServiceProvider.GetRequiredService(); + // Arrange + var entityName = "TestEntity"; + var dataFile = ""; // No headers in the file + var dataGroupId = 1; - // Act - var result = await _sut.StoreFileData(entityName, dataFile, dataGroupId); + // Act + var result = await _sut.StoreFileData(entityName, dataFile, dataGroupId); - // Assert - Assert.False(result); - Assert.Equal(1, await _dataContext.EdgeEntities.CountAsync()); - Assert.Equal(0, await _dataContext.EdgeAttributes.CountAsync()); - Assert.Equal(0, await _dataContext.EdgeValues.CountAsync()); - } + // Assert + Assert.False(result); + Assert.Equal(1, await _dataContext.EdgeEntities.CountAsync()); + Assert.Equal(0, await _dataContext.EdgeAttributes.CountAsync()); + Assert.Equal(0, await _dataContext.EdgeValues.CountAsync()); } } \ No newline at end of file diff --git a/mohaymen-codestar-Team02_XUnitTest/Servies/StorData/StoreDataServiceTest.cs b/mohaymen-codestar-Team02_XUnitTest/Servies/StorData/StoreDataServiceTest.cs index e1845e2..7e3bb9d 100644 --- a/mohaymen-codestar-Team02_XUnitTest/Servies/StorData/StoreDataServiceTest.cs +++ b/mohaymen-codestar-Team02_XUnitTest/Servies/StorData/StoreDataServiceTest.cs @@ -18,16 +18,15 @@ public StoreDataServiceTest() var serviceCollection = new ServiceCollection(); var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()) + .UseInMemoryDatabase(Guid.NewGuid().ToString()) .Options; serviceCollection.AddScoped(_ => new DataContext(options)); _serviceProvider = serviceCollection.BuildServiceProvider(); - IEdageStorer edageStorer = Substitute.For(); - IVertexStorer vertexStorer = Substitute.For(); + var edageStorer = Substitute.For(); + var vertexStorer = Substitute.For(); _sut = new StoreDataService(_serviceProvider, edageStorer, vertexStorer); - } [Fact] diff --git a/mohaymen-codestar-Team02_XUnitTest/Servies/StorData/VertexStorerCsvTest.cs b/mohaymen-codestar-Team02_XUnitTest/Servies/StorData/VertexStorerCsvTest.cs index 606e9d5..0a0ff82 100644 --- a/mohaymen-codestar-Team02_XUnitTest/Servies/StorData/VertexStorerCsvTest.cs +++ b/mohaymen-codestar-Team02_XUnitTest/Servies/StorData/VertexStorerCsvTest.cs @@ -3,72 +3,71 @@ using mohaymen_codestar_Team02.Data; using mohaymen_codestar_Team02.Services.StoreData; -namespace mohaymen_codestar_Team02_XUnitTest.Servies.StorData +namespace mohaymen_codestar_Team02_XUnitTest.Servies.StorData; + +public class VertexStorerCsvTests { - public class VertexStorerCsvTests + private VertexStorerCsv _sut; + private DataContext _dataContext; + private ServiceProvider _serviceProvider; + + public VertexStorerCsvTests() + { + var serviceCollection = new ServiceCollection(); + + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + + serviceCollection.AddScoped(_ => new DataContext(options)); + + _serviceProvider = serviceCollection.BuildServiceProvider(); + + _sut = new VertexStorerCsv(_serviceProvider); + using var scope = _serviceProvider.CreateScope(); + _dataContext = scope.ServiceProvider.GetRequiredService(); + } + + [Fact] + public async Task StoreFileData_ShouldReturnTrue_WhenDataIsValid() { - private VertexStorerCsv _sut; - private DataContext _dataContext; - private ServiceProvider _serviceProvider; - - public VertexStorerCsvTests() - { - var serviceCollection = new ServiceCollection(); - - var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()) - .Options; - - serviceCollection.AddScoped(_ => new DataContext(options)); - - _serviceProvider = serviceCollection.BuildServiceProvider(); - - _sut = new(_serviceProvider); - using var scope = _serviceProvider.CreateScope(); - _dataContext = scope.ServiceProvider.GetRequiredService(); - } - - [Fact] - public async Task StoreFileData_ShouldReturnTrue_WhenDataIsValid() - { - using var scope = _serviceProvider.CreateScope(); - _dataContext = scope.ServiceProvider.GetRequiredService(); - - // Arrange - string entityName = "TestEntity"; - string dataFile = "attribute1,attribute2\nvalue1,value2\nlol1,lol2"; - var dataGroupId = 1; - - - // Act - var result = await _sut.StoreFileData(entityName, dataFile, dataGroupId); - - // Assert - Assert.True(result); - Assert.Equal(1, await _dataContext.VertexEntities.CountAsync()); - Assert.Equal(1, await _dataContext.VertexAttributes.CountAsync()); - Assert.Equal(2, await _dataContext.VertexValues.CountAsync()); - } - - [Fact] - public async Task StoreFileData_ShouldReturnFalse_WhenHeaderLineIsNull() - { - using var scope = _serviceProvider.CreateScope(); - _dataContext = scope.ServiceProvider.GetRequiredService(); - - // Arrange - string entityName = "TestEntity"; - string dataFile = ""; - var dataGroupId = 1; - - // Act - var result = await _sut.StoreFileData(entityName, dataFile, dataGroupId); - - // Assert - Assert.False(result); - Assert.Equal(1, await _dataContext.VertexEntities.CountAsync()); - Assert.Equal(0, await _dataContext.VertexAttributes.CountAsync()); - Assert.Equal(0, await _dataContext.VertexValues.CountAsync()); - } + using var scope = _serviceProvider.CreateScope(); + _dataContext = scope.ServiceProvider.GetRequiredService(); + + // Arrange + var entityName = "TestEntity"; + var dataFile = "attribute1,attribute2\nvalue1,value2\nlol1,lol2"; + var dataGroupId = 1; + + + // Act + var result = await _sut.StoreFileData(entityName, dataFile, dataGroupId); + + // Assert + Assert.True(result); + Assert.Equal(1, await _dataContext.VertexEntities.CountAsync()); + Assert.Equal(1, await _dataContext.VertexAttributes.CountAsync()); + Assert.Equal(2, await _dataContext.VertexValues.CountAsync()); + } + + [Fact] + public async Task StoreFileData_ShouldReturnFalse_WhenHeaderLineIsNull() + { + using var scope = _serviceProvider.CreateScope(); + _dataContext = scope.ServiceProvider.GetRequiredService(); + + // Arrange + var entityName = "TestEntity"; + var dataFile = ""; + var dataGroupId = 1; + + // Act + var result = await _sut.StoreFileData(entityName, dataFile, dataGroupId); + + // Assert + Assert.False(result); + Assert.Equal(1, await _dataContext.VertexEntities.CountAsync()); + Assert.Equal(0, await _dataContext.VertexAttributes.CountAsync()); + Assert.Equal(0, await _dataContext.VertexValues.CountAsync()); } } \ No newline at end of file diff --git a/mohaymen-codestar-Team02_XUnitTest/Servies/TokenService/TokenServiceTest.cs b/mohaymen-codestar-Team02_XUnitTest/Servies/TokenService/TokenServiceTest.cs index aceac1f..9d7e7eb 100644 --- a/mohaymen-codestar-Team02_XUnitTest/Servies/TokenService/TokenServiceTest.cs +++ b/mohaymen-codestar-Team02_XUnitTest/Servies/TokenService/TokenServiceTest.cs @@ -31,7 +31,7 @@ public void GetUserNameFromToken_ShouldReturnUsername_WhenTokenIsValid() // Arrange var claims = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { - new Claim(ClaimTypes.Name, "testUser") + new(ClaimTypes.Name, "testUser") }, "mock")); var httpContext = Substitute.For(); @@ -64,7 +64,7 @@ public void GetUserNameFromToken_ShouldReturnNull_WhenUserHasNoNameClaim() // Arrange var claims = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { - new Claim(ClaimTypes.Email, "testuser@example.com") + new(ClaimTypes.Email, "testuser@example.com") }, "mock")); var httpContext = Substitute.For(); @@ -77,4 +77,4 @@ public void GetUserNameFromToken_ShouldReturnNull_WhenUserHasNoNameClaim() // Assert Assert.Null(username); } -} +} \ No newline at end of file diff --git a/mohaymen-codestar-Team02_XUnitTest/mohaymen-codestar-Team02_XUnitTest.csproj b/mohaymen-codestar-Team02_XUnitTest/mohaymen-codestar-Team02_XUnitTest.csproj index 96cddf5..01d4505 100644 --- a/mohaymen-codestar-Team02_XUnitTest/mohaymen-codestar-Team02_XUnitTest.csproj +++ b/mohaymen-codestar-Team02_XUnitTest/mohaymen-codestar-Team02_XUnitTest.csproj @@ -13,8 +13,8 @@ - runtime; build; native; contentfiles; analyzers; buildtransitive - all + runtime; build; native; contentfiles; analyzers; buildtransitive + all @@ -25,7 +25,7 @@ - +