Skip to content

Commit

Permalink
1
Browse files Browse the repository at this point in the history
  • Loading branch information
akbaramd committed Dec 30, 2024
1 parent 6ecd150 commit 4218cfc
Show file tree
Hide file tree
Showing 8 changed files with 59 additions and 51 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public async Task<TDbContext> GetDbContextAsync(bool isReadOnly = true,
throw new InvalidOperationException("DbContext must be used inside an active Unit of Work.");

// Check if the DbContext is already registered in the Unit of Work
var dbContextKey = typeof(TDbContext).FullName
var dbContextKey = typeof(TDbContext).FullName + "." + unitOfWork.Id.ToString()
?? throw new InvalidOperationException("The type name for the DbContext is null.");

if (unitOfWork.GetDataStorage(dbContextKey) is EfCoreUnitOfWOrtDatabaseManager existingStorage)
Expand Down
1 change: 1 addition & 0 deletions New/Payeh.SharedKernel/UnitOfWork/IUnitOfWork.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
{
public interface IUnitOfWork : IDisposable
{
public Guid Id { get; set; }
public IUnitOfWorkOptions Options { get; }
public event EventHandler? Disposed;
// Transaction Management
Expand Down
1 change: 1 addition & 0 deletions New/Payeh.SharedKernel/UnitOfWork/Null/NullUnitOfWork.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ namespace Payeh.SharedKernel.UnitOfWork.Null
{
public class NullUnitOfWork : IUnitOfWork
{
public Guid Id { get; set; } = Guid.NewGuid();
public IUnitOfWorkOptions Options { get; } = new UnitOfWorkOptions();
public event EventHandler? Disposed;

Expand Down
2 changes: 1 addition & 1 deletion New/Payeh.SharedKernel/UnitOfWork/UnitOfWork.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public class UnitOfWork : IUnitOfWork
private readonly Dictionary<string, IUnitOfWOrtDatabaseManager> _dataStorages = new();
private readonly IMediator _mediator;
private bool _isDisposed;

public Guid Id { get; set; } = Guid.NewGuid();
public IUnitOfWorkOptions Options { get; set; }
public event EventHandler? Disposed;

Expand Down
2 changes: 1 addition & 1 deletion Nezam.EES.Slice.Identity/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public static IServiceCollection AddIdentitySlice(this IServiceCollection servic
services.AddTransient<IUserDomainService, UserDomainService>();
services.AddTransient<IRoleDomainService, RoleDomainService>();

services.AddHostedService<IdentitySeedService>();
// services.AddHostedService<IdentitySeedService>();
services.AddTransient<IUserRepository, UserRepository>();
services.AddTransient<IRoleRepository, RoleRepository>();
return services;
Expand Down
98 changes: 52 additions & 46 deletions Nezam.EES/BackgroundService/EngineerUserSyncService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using (var scope = _serviceProvider.CreateScope())
{

var dbConnection = scope.ServiceProvider.GetRequiredService<IDbConnection>();
var userDomainService = scope.ServiceProvider.GetRequiredService<IUserDomainService>();
var roleDomainService = scope.ServiceProvider.GetRequiredService<IRoleDomainService>();
var unitOfWorkManager = scope.ServiceProvider.GetRequiredService<IUnitOfWorkManager>();

using var uowa = unitOfWorkManager.Begin(); // Begin UnitOfWork for the entire process

using var uowInit = scope.ServiceProvider.GetRequiredService<IUnitOfWorkManager>().Begin();

// Ensure the Engineer role exists
var engineerRoleId = RoleId.NewId("engineer");
var roleCheck = await roleDomainService.GetRoleByIdAsync(engineerRoleId);
Expand All @@ -43,61 +43,67 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
engineerRoleId = roleCheck.Data.RoleId;
}

await uowa.CommitAsync(stoppingToken);
await uowInit.CommitAsync(stoppingToken);

// Fetch all engineers from the tbl_engineers table
// Fetch the top 500 engineers from the tbl_engineers table
const string query = "SELECT TOP 500 ozviyat_no, name, password, fname, e_mail FROM tbl_engineers";

var engineers = await dbConnection.QueryAsync(query);

int index = 0; // Initialize the index
var total = engineers.Count();
foreach (var engineer in engineers)
{
using var uow = unitOfWorkManager.Begin(); // Begin UnitOfWork for each engineer

try
// Use a new scope for each engineer to ensure a fresh DbContext instance
using (var innerScope = _serviceProvider.CreateScope())
{

var username = engineer.ozviyat_no.ToString();
var firstName = engineer.name;
var password = ( engineer.password == null || engineer.password.Length < 3)? username: engineer.password;
var lastName = engineer.fname;
var email = engineer.e_mail;
// Ensure a new UnitOfWork with a separate DbContext
var uow = innerScope.ServiceProvider.GetRequiredService<IUnitOfWorkManager>().Begin();

// Check if the user already exists
var userCheck = await userDomainService.GetUserByUsernameAsync(UserNameId.NewId(username));
if (!userCheck.IsSuccess)
try
{
// Create a new user
var profile = new UserProfileValue(firstName, lastName);
var user = new UserEntity(
UserId.NewId(),
UserNameId.NewId(username),
new UserPasswordValue(password), // Default password
profile,
(!string.IsNullOrWhiteSpace(email) && UserEmailValue.IsValidEmail(email)) ? new UserEmailValue(email) : null
);
var userCreateResult = await userDomainService.Create(user);

// Assign the Engineer role to the new user
await userDomainService.AssignRoleAsync(userCreateResult.Data, new[] { engineerRoleId });
var username = engineer.ozviyat_no.ToString();
var firstName = engineer.name;
var password = engineer.password ?? username; // Fallback to ozviyat_no if no password
var lastName = engineer.fname;
var email = engineer.e_mail;

userDomainService = innerScope.ServiceProvider.GetRequiredService<IUserDomainService>();

// Check if the user already exists
var userCheck = await userDomainService.GetUserByUsernameAsync(UserNameId.NewId(username));
if (!userCheck.IsSuccess)
{
// Create a new user
var profile = new UserProfileValue(firstName, lastName);
var user = new UserEntity(
UserId.NewId(),
UserNameId.NewId(username),
new UserPasswordValue(password), // Default password
profile,
!string.IsNullOrWhiteSpace(email) && UserEmailValue.IsValidEmail(email) ? new UserEmailValue(email) : null
);
var userCreateResult = await userDomainService.Create(user);

// Assign the Engineer role to the new user
roleDomainService = innerScope.ServiceProvider.GetRequiredService<IRoleDomainService>();
await userDomainService.AssignRoleAsync(userCreateResult.Data, new[] { engineerRoleId });
}

// Commit changes for this engineer
await uow.CommitAsync(stoppingToken);

// Log the progress
Console.WriteLine($"Processed Engineer {index + 1}: {total}");

index++; // Increment the index after processing each engineer
}

await uow.CommitAsync(stoppingToken); // Commit after processing each engineer


}
catch (Exception ex)
{
await uow.RollbackAsync(stoppingToken); // Rollback if any error occurs
Console.WriteLine($"Error processing engineer {engineer.ozviyat_no}: {ex.Message}");
}

// Log the index and information
Console.WriteLine($"Processed Engineer {index + 1}:{total}");

index++; // Increment the index after processing each engineer
catch (Exception ex)
{
// Rollback on error
await uow.RollbackAsync(stoppingToken);
Console.WriteLine($"Error processing engineer {engineer.ozviyat_no}: {ex.Message}");
}
} // Disposes the inner scope and commits the UnitOfWork
}

// Log when the process is finished
Expand Down
2 changes: 1 addition & 1 deletion Nezam.EES/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=85.185.6.4;Initial Catalog=map;User ID=new_site_user;Password=111qqqAAAn;Trust Server Certificate=True;"
"DefaultConnection": "Data Source=85.185.6.4;Initial Catalog=Nezam.EES;User ID=new_site_user;Password=111qqqAAAn;Trust Server Certificate=True;"
},
"Jwt": {
"SecretKey": "YourSecretKey12dl2393743598y3u46hij45h6478r823",
Expand Down
2 changes: 1 addition & 1 deletion Nezam.EES/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=85.185.6.4;Initial Catalog=map;User ID=new_site_user;Password=111qqqAAAn;Trust Server Certificate=True;"
"DefaultConnection": "Data Source=85.185.6.4;Initial Catalog=Nezam.EES;User ID=new_site_user;Password=111qqqAAAn;Trust Server Certificate=True;"
},
"Jwt": {
"SecretKey": "YourSecretKey12dl2393743598y3u46hij45h6478r823",
Expand Down

0 comments on commit 4218cfc

Please sign in to comment.