Skip to content

Commit

Permalink
Merge pull request #44 from Ali-YousefiTelori/develop
Browse files Browse the repository at this point in the history
Check null exception
  • Loading branch information
Ali-YousefiTelori authored Sep 9, 2023
2 parents d1dd461 + 15fd6d8 commit 280e1a8
Show file tree
Hide file tree
Showing 13 changed files with 354 additions and 23 deletions.
29 changes: 25 additions & 4 deletions src/CSharp/EasyMicroservices.Cores.AspCore.Tests/BasicTests.cs
Original file line number Diff line number Diff line change
@@ -1,27 +1,31 @@
using EasyMicroservices.ServiceContracts;
using EasyMicroservices.Cores.Database.Managers;
using EasyMicroservices.Cores.Tests.Contracts.Common;
using EasyMicroservices.Cores.Tests.Laboratories;
using EasyMicroservices.ServiceContracts;
using Microsoft.AspNetCore.TestHost;
using Newtonsoft.Json;

namespace EasyMicroservices.Cores.AspCore.Tests
{
public class BasicTests
public class BasicTests : WhiteLabelLaboratoryTest
{
protected TestServer _testServer;
public BasicTests()
{
var webBuilder = new WebHostBuilder();
webBuilder.UseStartup<Startup>();

base.OnInitialize().Wait();
_testServer = new TestServer(webBuilder);
}

[Fact]
public async Task Get_EndpointsReturnSuccessAndCorrectContentType()
public async Task<string> Get_EndpointsReturnSuccessAndCorrectContentType()
{
var client = _testServer.CreateClient();
var data = await client.GetStringAsync($"api/user/getall");
var result = JsonConvert.DeserializeObject<MessageContract>(data);
Assert.True(result);
return data;
}

[Fact]
Expand All @@ -42,5 +46,22 @@ public async Task InternalErrorTest()
Assert.False(result);
Assert.Contains(result.Error.StackTrace, x => x.Contains("UserController.cs"));
}

[Fact]
public async Task AddUser()
{
var client = _testServer.CreateClient();
var data = await client.PostAsJsonAsync($"api/user/Add", new UpdateUserContract()
{
UserName = "Ali",
UniqueIdentity = "1-2"
});
var result = JsonConvert.DeserializeObject<MessageContract>(await data.Content.ReadAsStringAsync());
Assert.True(result);
var getAllRespone = await Get_EndpointsReturnSuccessAndCorrectContentType();
var users = JsonConvert.DeserializeObject<ListMessageContract<UpdateUserContract>>(getAllRespone);
Assert.True(users);
Assert.True(users.Result.All(x => DefaultUniqueIdentityManager.DecodeUniqueIdentity(x.UniqueIdentity).Length > 2));
}
}
}
10 changes: 1 addition & 9 deletions src/CSharp/EasyMicroservices.Cores.AspCore.Tests/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,6 @@ public void ConfigureServices(IServiceCollection services)
services.AddScoped((serviceProvider) => new UnitOfWork(serviceProvider).GetContractLogic<UserEntity, UserEntity, UserEntity, UserEntity>());
services.AddTransient(serviceProvider => new MyTestContext(serviceProvider.GetService<IEntityFrameworkCoreDatabaseBuilder>()));
services.AddScoped<IEntityFrameworkCoreDatabaseBuilder>(serviceProvider => new DatabaseBuilder());
//services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
// .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
// options =>
// {
// options.LoginPath = new PathString("/auth/login");
// options.AccessDeniedPath = new PathString("/auth/denied");
// });
//services.AddMvc().AddApplicationPart(typeof(UserController).Assembly).AddControllersAsServices();
}

public void Configure(IApplicationBuilder app)
Expand All @@ -41,7 +33,7 @@ public void Configure(IApplicationBuilder app)
{
endpoints.MapControllers();
});
app.Build<MyTestContext>();
app.Build<MyTestContext>().Wait();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<Platforms>AnyCPU;x64;x86</Platforms>
<Authors>EasyMicroservices</Authors>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>0.0.0.26</Version>
<Version>0.0.0.27</Version>
<Description>asp core servces.</Description>
<Copyright>[email protected]</Copyright>
<PackageTags>core,cores,base,database,services,asp,aspnet</PackageTags>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<Platforms>AnyCPU;x64;x86</Platforms>
<Authors>EasyMicroservices</Authors>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>0.0.0.7</Version>
<Version>0.0.0.8</Version>
<Description>asp core servces.</Description>
<Copyright>[email protected]</Copyright>
<PackageTags>core,cores,base,database,services,asp,aspnet,aspcore,efcore</PackageTags>
Expand All @@ -22,8 +22,9 @@
<PackageReference Include="EasyMicroservices.Serialization.Newtonsoft.Json" Version="0.0.0.3" />
<PackageReference Include="EasyMicroservices.Mapper.SerializerMapper" Version="0.0.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="EasyMicroservices.WhiteLabelsMicroservice.Clients" Version="0.0.0.6" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\EasyMicroservices.Cores.AspCoreApi\EasyMicroservices.Cores.AspCoreApi.csproj" />
<ProjectReference Include="..\EasyMicroservices.Cores.Relational.EntityFrameworkCore\EasyMicroservices.Cores.Relational.EntityFrameworkCore.csproj" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using EasyMicroservices.Cores.AspEntityFrameworkCoreApi;
using EasyMicroservices.Cores.Database.Managers;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using WhiteLables.GeneratedServices;

namespace EasyMicroservices.Cores.AspCoreApi.Managers
{
internal class WhiteLabelManager
{
internal WhiteLabelManager(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}

private readonly IServiceProvider _serviceProvider;
public static HttpClient HttpClient { get; set; } = new HttpClient();

string GetDefaultUniqueIdentity(ICollection<WhiteLabelContract> whiteLables, long? parentId)
{
var found = whiteLables.FirstOrDefault(x => x.ParentId == parentId);
if (found == null)
{
return "";
}
return $"{DefaultUniqueIdentityManager.GenerateUniqueIdentity(found.Id)}-{GetDefaultUniqueIdentity(whiteLables, found.Id)}".Trim('-');
}

public async Task Initialize(string microserviceName, string whiteLableRoute, params Type[] dbContextTypes)
{
if (dbContextTypes.IsNullOrEmpty())
return;
var whiteLabelClient = new WhiteLables.GeneratedServices.WhiteLabelClient(whiteLableRoute, HttpClient);
var whiteLabels = await whiteLabelClient.GetAllAsync().ConfigureAwait(false);
UnitOfWork.DefaultUniqueIdentity = GetDefaultUniqueIdentity(whiteLabels.Result, null);

var microserviceClient = new WhiteLables.GeneratedServices.MicroserviceClient(whiteLableRoute, HttpClient);
var microservices = await microserviceClient.GetAllAsync().ConfigureAwait(false);
var foundMicroservice = microservices.Result.FirstOrDefault(x => x.Name.Equals(microserviceName, StringComparison.OrdinalIgnoreCase));
if (foundMicroservice == null)
{
foundMicroservice = new WhiteLables.GeneratedServices.MicroserviceContract()
{
InstanceIndex = 1,
Name = microserviceName,
Description = "Automatically added"
};
var addMicroservice = await microserviceClient.AddAsync(foundMicroservice).ConfigureAwait(false);
foundMicroservice.Id = addMicroservice.Result;
}
UnitOfWork.MicroserviceId = foundMicroservice.Id;

var uniqueIdentityManager = new UnitOfWork(_serviceProvider).GetUniqueIdentityManager() as DefaultUniqueIdentityManager;

var microserviceContextTableClient = new WhiteLables.GeneratedServices.MicroserviceContextTableClient(whiteLableRoute, HttpClient);
var microserviceContextTables = await microserviceContextTableClient.GetAllAsync().ConfigureAwait(false);

HashSet<string> addedInWhitLabels = new HashSet<string>();
foreach (var contextTableContract in microserviceContextTables.Result)
{
uniqueIdentityManager.InitializeTables(contextTableContract.MicroserviceId, contextTableContract.ContextName, contextTableContract.TableName, contextTableContract.ContextTableId);
addedInWhitLabels.Add(uniqueIdentityManager.GetContextTableName(contextTableContract.MicroserviceId, contextTableContract.ContextName, contextTableContract.TableName));
}

foreach (var contextType in dbContextTypes)
{
var contextTableClient = new WhiteLables.GeneratedServices.ContextTableClient(whiteLableRoute, HttpClient);
var contextTables = await contextTableClient.GetAllAsync().ConfigureAwait(false);
using var insctanceOfContext = _serviceProvider.GetService(contextType) as DbContext;
string contextName = uniqueIdentityManager.GetContextName(contextType);
foreach (var entityType in insctanceOfContext.Model.GetEntityTypes())
{
string tableName = entityType.ServiceOnlyConstructorBinding.RuntimeType.Name;
var tableFullName = uniqueIdentityManager.GetContextTableName(foundMicroservice.Id, contextType.Name, tableName);
if (!addedInWhitLabels.Contains(tableFullName))
{
if (microserviceContextTables.Result.Any(x => x.ContextName == contextName && x.TableName == tableName && x.MicroserviceId == foundMicroservice.Id))
continue;
var contextTable = contextTables.Result.FirstOrDefault(x => x.ContextName == contextName && x.TableName == tableName);
if (contextTable == null)
{
contextTable = new WhiteLables.GeneratedServices.ContextTableContract()
{
ContextName = contextName,
TableName = tableName,
};
var contextTableResult = await contextTableClient.AddAsync(contextTable).ConfigureAwait(false);
contextTable.Id = contextTableResult.Result;
}
var addedMicroserviceContextTable = await microserviceContextTableClient.AddAsync(new WhiteLables.GeneratedServices.MicroserviceContextTableContract()
{
ContextName = contextName,
TableName = tableName,
MicroserviceName = microserviceName,
MicroserviceId = foundMicroservice.Id,
ContextTableId = contextTable.Id
}).ConfigureAwait(false);
uniqueIdentityManager.InitializeTables(foundMicroservice.Id, contextName, tableName, contextTable.Id);
}
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using System.Net;
using System.Net.Mime;
using System.Text.Json;
using System.Threading.Tasks;

namespace EasyMicroservices.Cores.AspEntityFrameworkCoreApi
{
Expand Down Expand Up @@ -90,7 +91,7 @@ public static void UseGlobalExceptionHandler(this IApplicationBuilder app)
/// <typeparam name="TContext"></typeparam>
/// <param name="app"></param>
/// <returns></returns>
public static void Build<TContext>(this IApplicationBuilder app)
public static async Task Build<TContext>(this IApplicationBuilder app)
where TContext : RelationalCoreContext
{
app.UseDeveloperExceptionPage();
Expand All @@ -107,6 +108,8 @@ public static void Build<TContext>(this IApplicationBuilder app)
var dbbuilder = new DatabaseCreator();
using var context = scope.ServiceProvider.GetRequiredService<TContext>();
dbbuilder.Initialize(context);
var uow = scope.ServiceProvider.GetRequiredService<IUnitOfWork>() as UnitOfWork;
await uow.Initialize("TextExample", "http://localhost:6041", typeof(TContext)).ConfigureAwait(false);
}
var build = app.Build();
app.Run(build);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using EasyMicroservices.Cores.AspEntityFrameworkCoreApi.Interfaces;
using EasyMicroservices.Cores.AspCoreApi.Managers;
using EasyMicroservices.Cores.AspEntityFrameworkCoreApi.Interfaces;
using EasyMicroservices.Cores.Database.Interfaces;
using EasyMicroservices.Cores.Database.Logics;
using EasyMicroservices.Cores.Database.Managers;
Expand Down Expand Up @@ -51,7 +52,10 @@ T AddDisposable<T>(T data)
/// <returns></returns>
public IDatabase GetDatabase()
{
return AddDisposable(new EntityFrameworkCoreDatabaseProvider(_service.GetService<RelationalCoreContext>()));
var context = _service.GetService<RelationalCoreContext>();
if (context == null)
throw new Exception("RelationalCoreContext is null, please add your context to RelationalCoreContext as Transit or Scope.\r\nExample : services.AddTransient<RelationalCoreContext>(serviceProvider => serviceProvider.GetService<YourDbContext>());");
return AddDisposable(new EntityFrameworkCoreDatabaseProvider(context));
}

/// <summary>
Expand Down Expand Up @@ -223,7 +227,11 @@ public virtual IEasyReadableQueryableAsync<TEntity> GetReadableQueryable<TEntity
public IDatabase GetDatabase<TContext>()
where TContext : RelationalCoreContext
{
return AddDisposable(new EntityFrameworkCoreDatabaseProvider(_service.GetService<TContext>()));
var context = _service.GetService<TContext>();
if (context == null)
throw new Exception("TContext is null, please add your context to Context as Transit or Scope.\r\nExample : services.AddTransient<YourContext>(serviceProvider => serviceProvider.GetService<YourDbContext>());");

return AddDisposable(new EntityFrameworkCoreDatabaseProvider(context));
}

/// <summary>
Expand Down Expand Up @@ -273,6 +281,18 @@ public IUniqueIdentityManager GetUniqueIdentityManager()
return UniqueIdentityManager;
}

/// <summary>
///
/// </summary>
/// <param name="microserviceName"></param>
/// <param name="whiteLableRoute"></param>
/// <param name="dbContextTypes"></param>
/// <returns></returns>
public Task Initialize(string microserviceName, string whiteLableRoute, params Type[] dbContextTypes)
{
return new WhiteLabelManager(_service).Initialize(microserviceName, whiteLableRoute, dbContextTypes);
}

/// <summary>
///
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<Platforms>AnyCPU;x64;x86</Platforms>
<Authors>EasyMicroservices</Authors>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>0.0.0.28</Version>
<Version>0.0.0.29</Version>
<Description>core of database.</Description>
<Copyright>[email protected]</Copyright>
<PackageTags>core,cores,base,database</PackageTags>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<Platforms>AnyCPU;x64;x86</Platforms>
<Authors>EasyMicroservices</Authors>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>0.0.0.19</Version>
<Version>0.0.0.20</Version>
<Description>ef core of database.</Description>
<Copyright>[email protected]</Copyright>
<PackageTags>core,cores,base,database,ef,efcore</PackageTags>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<Platforms>AnyCPU;x64;x86</Platforms>
<Authors>EasyMicroservices</Authors>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>0.0.0.16</Version>
<Version>0.0.0.17</Version>
<Description>ef core of Relational database.</Description>
<Copyright>[email protected]</Copyright>
<PackageTags>core,cores,base,database,ef,efcore,Relational</PackageTags>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,8 @@ Type[] GetAllBases(Type type)

string[] GetSimplifyPropertyName(string name)
{
if (IrregularVerbs.TryGetValue(name, out string value))
return new string[] { value };
string entity = "es";
if (name.EndsWith(entity))
return GetEndOfCollectionNames(name[..^entity.Length]);
Expand All @@ -157,6 +159,39 @@ string[] GetSimplifyPropertyName(string name)
return new string[] { name };
}

static readonly Dictionary<string, string> IrregularVerbs = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "Man" , "Men" },
{ "Child" , "Children" },
{ "Parent" , "Children" },
{ "Tooth" , "Teeth" },
{ "Foot" , "Feet" },
{ "Person" , "People" },
{ "Leaf" , "Leaves" },
{ "Mouse" , "Mice" },
{ "Goose" , "Geese" },
{ "Half" , "Halves" },
{ "Knife" , "Knives" },
{ "Wife" , "Wives" },
{ "Life" , "Lives" },
{ "Elf" , "Elves" },
{ "Loaf" , "Loaves" },
{ "Potato" , "Potatoes" },
{ "Tomato" , "Tomatoes" },
{ "Cactus" , "Cacti" },
{ "Focus" , "Foci" },
{ "Fungus" , "Fungi" },
{ "Nucleus" , "Nuclei" },
{ "Syllabus" , "Syllabuses" },
{ "Analysis" , "Analyses" },
{ "Diagnosis" , "Diagnoses" },
{ "Oasis" , "Oases" },
{ "Thesis" , "Theses" },
{ "Crisis" , "Crises" },
{ "Phenomenon" , "Phenomena" },
{ "Criterion" , "Criteria" },
{ "Datum" , "Data" },
};
string[] GetEndOfCollectionNames(string name)
{
List<string> names = new List<string>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="EasyMicroservices.Laboratory" Version="0.0.0.7" />
<PackageReference Include="EasyMicroservices.Mapper.CompileTimeMapper" Version="0.0.0.5" />
<PackageReference Include="EasyMicroservices.Mapper.SerializerMapper" Version="0.0.0.2" />
<PackageReference Include="EasyMicroservices.Serialization.Newtonsoft.Json" Version="0.0.0.3" />
Expand All @@ -24,6 +25,7 @@

<ItemGroup>
<ProjectReference Include="..\EasyMicroservices.Cores.AspCoreApi\EasyMicroservices.Cores.AspCoreApi.csproj" />
<ProjectReference Include="..\EasyMicroservices.Cores.AspEntityFrameworkCoreApi\EasyMicroservices.Cores.AspEntityFrameworkCoreApi.csproj" />
<ProjectReference Include="..\EasyMicroservices.Cores.Contracts\EasyMicroservices.Cores.Contracts.csproj" />
<ProjectReference Include="..\EasyMicroservices.Cores.Database\EasyMicroservices.Cores.Database.csproj" />
<ProjectReference Include="..\EasyMicroservices.Cores.EntityFrameworkCore\EasyMicroservices.Cores.EntityFrameworkCore.csproj" />
Expand Down
Loading

0 comments on commit 280e1a8

Please sign in to comment.