antimatter8189
antimatter8189
CC#
Created by antimatter8189 on 1/10/2024 in #help
Any WinForms gods here? Having issues with the Editor Attribute
I am encountering an issue with a software project restructuring. Initially, my solution combined server classes and UI components in a single project. To improve the architecture, I separated these into distinct UI and server projects. However, this has led to a challenge: the server can no longer directly access the UI. To elaborate, in the original setup within a unified project, I had 'ClassA' inheriting from 'UITypeEditor'. 'ClassB' utilized the attribute Editor[typeof(ClassA), typeof(UITypeEditor)]. Now, with 'ClassA' residing in a different project, I created 'ClassC' which inherits from 'ClassB' and also applies the Editor[typeof(ClassA), typeof(UITypeEditor)] attribute. The issue arises when implementing this change: the 'EditorBaseTypeName' returns as 'string' instead of the expected 'assemblyQualifiedName'. I am seeking suggestions for addressing this problem. It's also worth noting that these properties lack setters, so overriding them is not an option
1 replies
CC#
Created by antimatter8189 on 8/27/2023 in #help
❔ Losing bytes when delivering dynamic object via RabbitMQ
Hey there got a bit of a complex problem. Got this code:
public static object ToDynamicClass(this ExpandoObject expando)
{
AssemblyName assemblyName = new AssemblyName("DynamicAssembly");
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicModule");
TypeBuilder typeBuilder = moduleBuilder.DefineType("DynamicType", TypeAttributes.Public);

foreach (var kvp in expando)
{
Type type = kvp.Value?.GetType() ?? typeof(object);
FieldBuilder field = typeBuilder.DefineField("_" + kvp.Key, type, FieldAttributes.Private);
PropertyBuilder property = typeBuilder.DefineProperty(kvp.Key, PropertyAttributes.HasDefault, type, null);

MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;

MethodBuilder currGetPropMthdBldr = typeBuilder.DefineMethod("get_" + kvp.Key, getSetAttr, type, Type.EmptyTypes);
ILGenerator currGetIL = currGetPropMthdBldr.GetILGenerator();
currGetIL.Emit(OpCodes.Ldarg_0);
currGetIL.Emit(OpCodes.Ldfld, field);
currGetIL.Emit(OpCodes.Ret);

//Some code removed because of character limit

property.SetGetMethod(currGetPropMthdBldr);
property.SetSetMethod(currSetPropMthdBldr);
}

Type objType = typeBuilder.CreateType();

object obj = Activator.CreateInstance(objType);
foreach (var kvp in expando)
{
objType.GetProperty(kvp.Key)?.SetValue(obj, kvp.Value);
}

return obj;
}
public static object ToDynamicClass(this ExpandoObject expando)
{
AssemblyName assemblyName = new AssemblyName("DynamicAssembly");
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicModule");
TypeBuilder typeBuilder = moduleBuilder.DefineType("DynamicType", TypeAttributes.Public);

foreach (var kvp in expando)
{
Type type = kvp.Value?.GetType() ?? typeof(object);
FieldBuilder field = typeBuilder.DefineField("_" + kvp.Key, type, FieldAttributes.Private);
PropertyBuilder property = typeBuilder.DefineProperty(kvp.Key, PropertyAttributes.HasDefault, type, null);

MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;

MethodBuilder currGetPropMthdBldr = typeBuilder.DefineMethod("get_" + kvp.Key, getSetAttr, type, Type.EmptyTypes);
ILGenerator currGetIL = currGetPropMthdBldr.GetILGenerator();
currGetIL.Emit(OpCodes.Ldarg_0);
currGetIL.Emit(OpCodes.Ldfld, field);
currGetIL.Emit(OpCodes.Ret);

//Some code removed because of character limit

property.SetGetMethod(currGetPropMthdBldr);
property.SetSetMethod(currSetPropMthdBldr);
}

Type objType = typeBuilder.CreateType();

object obj = Activator.CreateInstance(objType);
foreach (var kvp in expando)
{
objType.GetProperty(kvp.Key)?.SetValue(obj, kvp.Value);
}

return obj;
}
Before when i tried to send the ExpandoObj itself all worked well. Now Im sending a lift of objects the above methods produces using rabbitmq. when i seralize i got a 1500 bytes messege size, when i recive the messege its only 120 bytes. Any ideas what could be wrong?
11 replies
CC#
Created by antimatter8189 on 8/22/2023 in #help
❔ How to force enumaration on ExpandoObj?
Hey guys, i encountered a situation where i have this ExpandoObj I need to enumerate its properties (so it doesnt deffer execution on some event i have) Problem is, nothing seems to work. tried using like aka :
objectlist.Select(x=>{return x}).ToArray()
objectlist.Select(x=>{return x}).ToArray()
In addition tried going over the expandoobj with
foreach (var obj in objectList.OfType<ExpandoObject>())
{
var dictionaryView = obj as IDictionary<string, object>;
foreach (var key in dictionaryView.Keys.ToList()) // .ToList() is crucial to avoid collection modification issues.
{
var value = dictionaryView[key];
}
}
foreach (var obj in objectList.OfType<ExpandoObject>())
{
var dictionaryView = obj as IDictionary<string, object>;
foreach (var key in dictionaryView.Keys.ToList()) // .ToList() is crucial to avoid collection modification issues.
{
var value = dictionaryView[key];
}
}
And still when I hover over the objectList i get a "result view" and "dynamicview" which means it hasnt been enumarated.
3 replies
CC#
Created by antimatter8189 on 5/13/2023 in #help
❔ .Net Logging - Is this valid?
So i saw this nick chapsas short and I've too passed my message as a string(big error) into the logger. Aka this one: (60 sec video)https://www.youtube.com/shorts/PvQGVmozCdU So I've changed my method to do this:
public static class LoggerExtension
{
public static void LogWithDetails(
ILogger logger,
LogLevel logLevel,
object[] args,

string message,
[CallerFilePath] string filePath = "",
[CallerMemberName] string functionName = "",
[CallerLineNumber] int lineNumber = 0)
{
var fileName = System.IO.Path.GetFileName(filePath);
var messageTemplate = "{FileName}:{LineNumber} - {FunctionName}(): " + message;
var finalArgs = new List<object> { fileName, lineNumber, functionName };
finalArgs.AddRange(args);
logger.Log(logLevel, messageTemplate, finalArgs.ToArray());
}
}
public static class LoggerExtension
{
public static void LogWithDetails(
ILogger logger,
LogLevel logLevel,
object[] args,

string message,
[CallerFilePath] string filePath = "",
[CallerMemberName] string functionName = "",
[CallerLineNumber] int lineNumber = 0)
{
var fileName = System.IO.Path.GetFileName(filePath);
var messageTemplate = "{FileName}:{LineNumber} - {FunctionName}(): " + message;
var finalArgs = new List<object> { fileName, lineNumber, functionName };
finalArgs.AddRange(args);
logger.Log(logLevel, messageTemplate, finalArgs.ToArray());
}
}
Calling it like this:
LoggerExtension.LogWithDetails(_logger, LogLevel.Information, "number of phases to process = {Count}", new object[] { createdLesson.Phases.Count });
LoggerExtension.LogWithDetails(_logger, LogLevel.Information, "number of phases to process = {Count}", new object[] { createdLesson.Phases.Count });
Wanted to make sure this is correct and am not shooting myself in the foot
97 replies
CC#
Created by antimatter8189 on 5/9/2023 in #help
❔ Ef core-Odd Behavior
So straight into it, The mapping: builder.Entity<LessonPhase>(b => { b.ToTable(lingumindConsts.DbTablePrefix + "Phases", lingumindConsts.DbSchema); b.HasOne(x => x.BotInitialInteraction).WithOne(x => x.LessonPhaseForInitial) .HasForeignKey<BotInteraction>(x => x.LessonPhaseForInitialId); b.HasOne(x => x.BotFinalInteractionOnSuccess).WithOne(x => x.LessonPhaseForOnSuccess) .HasForeignKey<BotInteraction>(x => x.LessonPhaseForOnSuccessId); b.HasOne(x => x.BotFinalInteractionOnFailure).WithOne(x => x.LessonPhaseForOnFailure) .HasForeignKey<BotInteraction>(x => x.LessonPhaseForOnFailureId); b.HasMany(x => x.UserInteractions).WithOne(x => x.LessonPhase).HasForeignKey(x => x.LessonPhaseId); }); The Class:
public class LessonPhase : AuditedEntity<Guid>, ISoftDelete
{

}
public BotInteraction BotInitialInteraction { get; set; }
public BotInteraction? BotFinalInteractionOnSuccess { get; set; }
public BotInteraction? BotFinalInteractionOnFailure { get; set; }
public string? UserExpectedAnswer { get; set; }
public ICollection<UserInteraction> UserInteractions { get; set; }

public LessonPhase(Guid id) : base(id)
{
UserInteractions = new Collection<UserInteraction>();
}}
public class LessonPhase : AuditedEntity<Guid>, ISoftDelete
{

}
public BotInteraction BotInitialInteraction { get; set; }
public BotInteraction? BotFinalInteractionOnSuccess { get; set; }
public BotInteraction? BotFinalInteractionOnFailure { get; set; }
public string? UserExpectedAnswer { get; set; }
public ICollection<UserInteraction> UserInteractions { get; set; }

public LessonPhase(Guid id) : base(id)
{
UserInteractions = new Collection<UserInteraction>();
}}
The Code:

_currentLesson = await HandlePhaseAudioFileStorage(_currentLesson);
if (AzureBlobStorageManager.StoreEnabled) {
var newLesson=await _lessonRepository.InsertAsync(_currentLesson, true);

}

_currentLesson = await HandlePhaseAudioFileStorage(_currentLesson);
if (AzureBlobStorageManager.StoreEnabled) {
var newLesson=await _lessonRepository.InsertAsync(_currentLesson, true);

}
Basically After saving to the DB, the last phase, lets say number 6, The InitialBotInteraction string value becomes the same as the BotFinalInteractionOnSuccess string, Only happens on the last phase all the others are fine, so the heck is going on?
31 replies
CC#
Created by antimatter8189 on 5/4/2023 in #help
❔ Ef core creating shadow foreign key, why?
Got this error:
The foreign key property 'LessonPhase.LessonId1' was created in shadow state because a conflicting property with the simple name 'LessonId' exists in the entity type, but is either not mapped, is already used for another relationship, or is incompatible with the associated primary key type
The foreign key property 'LessonPhase.LessonId1' was created in shadow state because a conflicting property with the simple name 'LessonId' exists in the entity type, but is either not mapped, is already used for another relationship, or is incompatible with the associated primary key type
The classes:
public class LessonPhase : Entity<Guid>, ISoftDelete
{
public required int PhaseNumber { get; init; }
public int NumberOfExplanationRequestsMade { get; set; }
public Lesson Lesson { get; init; }
public Guid LessonId { get; init; }
public bool IsDeleted { get; set; }
public class LessonPhase : Entity<Guid>, ISoftDelete
{
public required int PhaseNumber { get; init; }
public int NumberOfExplanationRequestsMade { get; set; }
public Lesson Lesson { get; init; }
public Guid LessonId { get; init; }
public bool IsDeleted { get; set; }
public class Lesson : FullAuditedAggregateRootWithUser<Guid, IdentityUser>
{
public required string LessonSrcLanguage { get; init; }
public required string LessonDstLanguage { get; init; }
public int LessonNumber { get; set; }
public int LessonDifficulty { get; init; }
public required LessonState LessonState { get; set; }
public ICollection<LessonPhase> Phases { get; set; }
public LessonPhase CurrentPhase { get; set; }

public Lesson()
{
Phases = new Collection<LessonPhase>();
}
}
public class Lesson : FullAuditedAggregateRootWithUser<Guid, IdentityUser>
{
public required string LessonSrcLanguage { get; init; }
public required string LessonDstLanguage { get; init; }
public int LessonNumber { get; set; }
public int LessonDifficulty { get; init; }
public required LessonState LessonState { get; set; }
public ICollection<LessonPhase> Phases { get; set; }
public LessonPhase CurrentPhase { get; set; }

public Lesson()
{
Phases = new Collection<LessonPhase>();
}
}
Mapping:
builder.Entity<Lesson>(b =>
{
b.ToTable(lingumindConsts.DbTablePrefix + "Lessons", lingumindConsts.DbSchema);
b.ConfigureByConvention(); //auto configure for the base class props
});

builder.Entity<LessonPhase>(b =>
{
b.ToTable(lingumindConsts.DbTablePrefix + "Phases", lingumindConsts.DbSchema);
b.HasOne(x => x.Lesson).WithMany(x => x.Phases).HasForeignKey(x => x.LessonId);
builder.Entity<Lesson>(b =>
{
b.ToTable(lingumindConsts.DbTablePrefix + "Lessons", lingumindConsts.DbSchema);
b.ConfigureByConvention(); //auto configure for the base class props
});

builder.Entity<LessonPhase>(b =>
{
b.ToTable(lingumindConsts.DbTablePrefix + "Phases", lingumindConsts.DbSchema);
b.HasOne(x => x.Lesson).WithMany(x => x.Phases).HasForeignKey(x => x.LessonId);
Any idea? Cant seem to resolve this
17 replies
CC#
Created by antimatter8189 on 4/29/2023 in #help
❔ Advice on data modeling
So basically I've got this fat object called lesson, Each lesson has phases, which is basically a question Howerver such a situation can occur:
bot: some explanation... question
user: wrong answer
bot: not quire right.
user: wrong answer 2
bot: not exactly, try...
user: correct answer
bot: great job!
bot: some explanation... question
user: wrong answer
bot: not quire right.
user: wrong answer 2
bot: not exactly, try...
user: correct answer
bot: great job!
So each phase has user answers, I will add a collection of Bot Responses, How do I tie these 2 together? so they know the order and what they belong too? Any advice is welcome. using Ef core btw
3 replies
CC#
Created by antimatter8189 on 4/28/2023 in #help
❔ Whats the feature called?
I remember seeing a nick chapsas video where you can specify the string type for the Ide and get assistance from the ide and error highlighting, if the string is a json you declare it so and it knows how to work with it, its not raw string literals
5 replies
CC#
Created by antimatter8189 on 4/27/2023 in #help
❔ How does one hold a value in a private field in a controller?
So basically controller gets created for every request right? Problem is i have this field:
private Lesson _CurrentUserLesson
private Lesson _CurrentUserLesson
And i set it once the user creates a new lesson. However if you call another endpoint that uses that variable it becomes null, static wont do either as i read. So how do you approach this?
113 replies
CC#
Created by antimatter8189 on 4/14/2023 in #help
❔ Advice on Data modeling-ef core
Basically I've got a lesson which is an aggregate root, On said lesson i got phases and each phase has an answer. I want to be able to save past answers aswell to analyze. Current Code:
return queryable

.Include(x => x.LessonState)
.Include(x=>x.Phases).ThenInclude(x=>x.UserAnswer);
}
return queryable

.Include(x => x.LessonState)
.Include(x=>x.Phases).ThenInclude(x=>x.UserAnswer);
}
So I've come up with 2 approaches: 1.A phase will contain a list of answers and we will only load the last added to the db when making calls, Was unsure how to do it and Chat-gpt gave me this:
return queryable
.Include(x => x.LessonState)
.Select(x => new
{
Entity = x,
Phases = x.Phases.Select(p => new
{
Phase = p,
LastUserAnswer = p.UserAnswers.OrderByDescending(ua => ua.Id).FirstOrDefault()
})
})
.ToList()
.Select(x => new YourEntity
{
// Map other properties from x.Entity to the new YourEntity object
LessonState = x.Entity.LessonState,
Phases = x.Phases.Select(p => new YourPhaseClass
{
// Map other properties from p.Phase to the new YourPhaseClass object
UserAnswer = p.LastUserAnswer
}).ToList()
})
.AsQueryable();
return queryable
.Include(x => x.LessonState)
.Select(x => new
{
Entity = x,
Phases = x.Phases.Select(p => new
{
Phase = p,
LastUserAnswer = p.UserAnswers.OrderByDescending(ua => ua.Id).FirstOrDefault()
})
})
.ToList()
.Select(x => new YourEntity
{
// Map other properties from x.Entity to the new YourEntity object
LessonState = x.Entity.LessonState,
Phases = x.Phases.Select(p => new YourPhaseClass
{
// Map other properties from p.Phase to the new YourPhaseClass object
UserAnswer = p.LastUserAnswer
}).ToList()
})
.AsQueryable();
2.create a new entity named pastAnswer that sits on Phase, but doesnt load it except for when we want to load it for something And when the user submits a new answer, it gets saved as a past answer, and the new answer becomes the user answer
9 replies
CC#
Created by antimatter8189 on 4/13/2023 in #help
❔ Any way to optimize this? Task.WhenAll
This takes anywhere from 6-14 seconds, Any way to make it faster?
private async Task HandlePhaseAudioFileStorage()
{
var tasks = new List<Task>();
foreach (var phase in _currentLesson.Phases)
{
// Generate default bot audio if not provided
if (phase.BotAudio is null)
{
phase.BotAudio = await _googleApiManager.TextToSpeechAsync(phase.BotText, _srcLanguageCode);
var defaultBotBlobKey = _azureBlobStorageManager.GenerateBlobKey();
phase.DefaultPhaseBlobFileId = defaultBotBlobKey;
var botAudioWithTranslation = new AudioAndTranslation(phase.BotAudio, phase.BotText);
tasks.Add(_azureBlobStorageManager.SaveServerGeneratedFilesBytesAsync(defaultBotBlobKey,
botAudioWithTranslation));
}
if (phase.BotResponseTextOnSuccess is not null)
{
var successBotBlobKey = _azureBlobStorageManager.GenerateBlobKey();
phase.SuccessPhaseBlobFileId = successBotBlobKey;

var botSuccessAudioTask = phase.BotResponseAudioOnSuccess is not null
? Task.FromResult(phase.BotResponseAudioOnSuccess)
: _googleApiManager.TextToSpeechAsync(phase.BotResponseTextOnSuccess, _srcLanguageCode);

tasks.Add(botSuccessAudioTask.ContinueWith(async (botSuccessAudioTaskResult) =>
{
var botSuccessAudio = await botSuccessAudioTaskResult;
var botSuccessAudioWithTranslation =
new AudioAndTranslation(botSuccessAudio, phase.BotResponseTextOnSuccess);
await _azureBlobStorageManager.SaveServerGeneratedFilesBytesAsync(successBotBlobKey,
botSuccessAudioWithTranslation);
}));
}

}
}

await Task.WhenAll(tasks);
}
private async Task HandlePhaseAudioFileStorage()
{
var tasks = new List<Task>();
foreach (var phase in _currentLesson.Phases)
{
// Generate default bot audio if not provided
if (phase.BotAudio is null)
{
phase.BotAudio = await _googleApiManager.TextToSpeechAsync(phase.BotText, _srcLanguageCode);
var defaultBotBlobKey = _azureBlobStorageManager.GenerateBlobKey();
phase.DefaultPhaseBlobFileId = defaultBotBlobKey;
var botAudioWithTranslation = new AudioAndTranslation(phase.BotAudio, phase.BotText);
tasks.Add(_azureBlobStorageManager.SaveServerGeneratedFilesBytesAsync(defaultBotBlobKey,
botAudioWithTranslation));
}
if (phase.BotResponseTextOnSuccess is not null)
{
var successBotBlobKey = _azureBlobStorageManager.GenerateBlobKey();
phase.SuccessPhaseBlobFileId = successBotBlobKey;

var botSuccessAudioTask = phase.BotResponseAudioOnSuccess is not null
? Task.FromResult(phase.BotResponseAudioOnSuccess)
: _googleApiManager.TextToSpeechAsync(phase.BotResponseTextOnSuccess, _srcLanguageCode);

tasks.Add(botSuccessAudioTask.ContinueWith(async (botSuccessAudioTaskResult) =>
{
var botSuccessAudio = await botSuccessAudioTaskResult;
var botSuccessAudioWithTranslation =
new AudioAndTranslation(botSuccessAudio, phase.BotResponseTextOnSuccess);
await _azureBlobStorageManager.SaveServerGeneratedFilesBytesAsync(successBotBlobKey,
botSuccessAudioWithTranslation);
}));
}

}
}

await Task.WhenAll(tasks);
}
142 replies
CC#
Created by antimatter8189 on 4/4/2023 in #help
❔ Google Api- PermissionDenied
Facing an access problem using the google Api NuGet:
`Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", _googleApiParams.CredentialsPath /path to JSON file/);
_translationClient = TranslationServiceClient.Create();

DetectLanguageRequest request = new()
{
Parent = "projects/my-project-name",
Content = "this is a detection test"
};
`Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", _googleApiParams.CredentialsPath /path to JSON file/);
_translationClient = TranslationServiceClient.Create();

DetectLanguageRequest request = new()
{
Parent = "projects/my-project-name",
Content = "this is a detection test"
};
My Error: the exception:
`Grpc.Core.RpcException: 'Status(StatusCode="PermissionDenied", Detail="Cloud IAM permission 'cloudtranslate.languageDetectionModels.predict' denied. ")
`Grpc.Core.RpcException: 'Status(StatusCode="PermissionDenied", Detail="Cloud IAM permission 'cloudtranslate.languageDetectionModels.predict' denied. ")
This python code works howerver:
`self.translate_client = translate.Client.from_service_account_json(self.google_api_credentials_json_path)
translated_text = self.translate_client.translate(values="this is a test", target_language=target_language,
`self.translate_client = translate.Client.from_service_account_json(self.google_api_credentials_json_path)
translated_text = self.translate_client.translate(values="this is a test", target_language=target_language,
Any Ideas for a fix?
13 replies
CC#
Created by antimatter8189 on 4/3/2023 in #help
❔ Dependency injection fails-Value cannot be null
Kinda straightforward , here is the code:
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddSingleton<LessonParametersService>();

Configure<AbpAutoMapperOptions>(options =>
{
options.AddMaps<lingumindApplicationModule>();
});
getResults(context);


}

private void getResults(ServiceConfigurationContext context)
{
var lessonParametersService = context.Services.GetRequiredService<LessonParametersService>();
var result = lessonParametersService.getResult().GetAwaiter().GetResult();
}
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddSingleton<LessonParametersService>();

Configure<AbpAutoMapperOptions>(options =>
{
options.AddMaps<lingumindApplicationModule>();
});
getResults(context);


}

private void getResults(ServiceConfigurationContext context)
{
var lessonParametersService = context.Services.GetRequiredService<LessonParametersService>();
var result = lessonParametersService.getResult().GetAwaiter().GetResult();
}
Any ideas?
2 replies
CC#
Created by antimatter8189 on 3/19/2023 in #help
❔ Troubleshooting EF Core: Error Message - INSERT Statement Conflicts with FOREIGN KEY Constraint
Hey there facing an issue, I got a lesson entity that contains a List of questions. Mapping is done like this:
b.HasMany(x => x.Questions).WithOne(x => x.Lesson).HasForeignKey(x => x.LessonId).IsRequired();
b.HasMany(x => x.Questions).WithOne(x => x.Lesson).HasForeignKey(x => x.LessonId).IsRequired();
I am getting an exception when attempting to insert a new lesson, and my assumption is that the foreign key constraint on the questions array is failing because the lesson does not yet have an ID. As a result, the questions array is missing the required foreign key reference to the newly created lesson. Here is an example of the JSON data I am using:
{

"lessonNumber": 0,
"lessonDifficulty": 0,
"questions": [
{
"questionText": "string",
"questionNumber": 0
}
],
"lessonName": "string"
}
{

"lessonNumber": 0,
"lessonDifficulty": 0,
"questions": [
{
"questionText": "string",
"questionNumber": 0
}
],
"lessonName": "string"
}
Method like this:
public async Task<LessonDTO> CreateAsync(CreateLessonDTO input)
{
try
{
var lessonCount = await _lessonRepository.CountAsync(x => x.CreatorId == CurrentUser.Id);
var lesson = ObjectMapper.Map<CreateLessonDTO, Lesson>(input);
lesson.LessonNumber = lessonCount + 1;
lesson.CreatorId = CurrentUser.Id;
lesson.isServerGenerated = false;
lesson = await _lessonRepository.InsertAsync(lesson);
_activeLesson=lesson;
await UpdateLessonStateAsync(true);
UpdatePrivateFields(lesson);

return ObjectMapper.Map<Lesson, LessonDTO>(lesson);
}
catch (Exception ex)
{
// Handle the exception here, or re-throw it if appropriate
throw new Exception("An error occurred while creating the lesson.", ex);
}
}
public async Task<LessonDTO> CreateAsync(CreateLessonDTO input)
{
try
{
var lessonCount = await _lessonRepository.CountAsync(x => x.CreatorId == CurrentUser.Id);
var lesson = ObjectMapper.Map<CreateLessonDTO, Lesson>(input);
lesson.LessonNumber = lessonCount + 1;
lesson.CreatorId = CurrentUser.Id;
lesson.isServerGenerated = false;
lesson = await _lessonRepository.InsertAsync(lesson);
_activeLesson=lesson;
await UpdateLessonStateAsync(true);
UpdatePrivateFields(lesson);

return ObjectMapper.Map<Lesson, LessonDTO>(lesson);
}
catch (Exception ex)
{
// Handle the exception here, or re-throw it if appropriate
throw new Exception("An error occurred while creating the lesson.", ex);
}
}
4 replies
CC#
Created by antimatter8189 on 3/11/2023 in #help
❔ How would you write this service better?
The service:
23 replies
CC#
Created by antimatter8189 on 3/11/2023 in #help
❔ Is saving data from DB into private fields is a good idea?
Lets say i have this class:
public class LessonAppService :ApplicationService,
ILessonService //implement the IBookAppService
{

private List<Lesson> _UserLessons;
}
public class LessonAppService :ApplicationService,
ILessonService //implement the IBookAppService
{

private List<Lesson> _UserLessons;
}
And this method:
public async Task<List<LessonDTO>> GetUserLessons()

{
var queryable = await _lessonRepository.WithDetailsAsync();
var lessonsQuery= queryable.Where(x=>x.CreatorId == CurrentUser.Id).OrderBy(x=>x.LessonNumber).Take(20);
var lessons = await lessonsQuery.ToListAsync();
_UserLessons = lessons;
return ObjectMapper.Map<List<Lesson>, List<LessonDTO>>(lessons);

}
public async Task<List<LessonDTO>> GetUserLessons()

{
var queryable = await _lessonRepository.WithDetailsAsync();
var lessonsQuery= queryable.Where(x=>x.CreatorId == CurrentUser.Id).OrderBy(x=>x.LessonNumber).Take(20);
var lessons = await lessonsQuery.ToListAsync();
_UserLessons = lessons;
return ObjectMapper.Map<List<Lesson>, List<LessonDTO>>(lessons);

}
Would it be good to operate on that private field of entites instead of making additional DB calls? Same for example :
private Lesson _activeLesson;
private Lesson _activeLesson;
Any ideas?
6 replies
CC#
Created by antimatter8189 on 3/6/2023 in #help
❔ Using mvvm toolkit- Why my view has no access to my command?
I got the following Code in the view model:
[RelayCommand]
public void CalculateAndSave()
[RelayCommand]
public void CalculateAndSave()
And the view:
And in the View:
<Window x:Class="Calculator.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:VM="clr-namespace:Calculator.ViewModels"
xmlns:local="clr-namespace:Calculator"
mc:Ignorable="d"
Title="MainWindow" Height="525" Width="350">
<Window.DataContext>
<VM:CalculatorVM/>
</Window.DataContext>
And in the View:
<Window x:Class="Calculator.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:VM="clr-namespace:Calculator.ViewModels"
xmlns:local="clr-namespace:Calculator"
mc:Ignorable="d"
Title="MainWindow" Height="525" Width="350">
<Window.DataContext>
<VM:CalculatorVM/>
</Window.DataContext>
I got a few button on the view, when it try to give the button a command to CalculateAndSave, method isn't available, is my binding wrong?
124 replies
CC#
Created by antimatter8189 on 3/4/2023 in #help
❔ How do I use the appsetting.development?
Hey i got 2 files, 1 for prod 1 for development, i want to load the dev one when im working on my machine, whats the best way to do it?
9 replies
CC#
Created by antimatter8189 on 2/26/2023 in #help
❔ How to use the Azure function I built to retrieve the connection string? cant puzzle the pieces.
I have this function:
public static class Function1
{
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");

string name = req.Query["name"];
string ENVIROMENT = Environment.GetEnvironmentVariable("ConnectionStrings:Default");

string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;

string responseMessage = string.IsNullOrEmpty(name)
? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
: $" {ENVIROMENT}";

return new OkObjectResult(responseMessage);
}


}
public static class Function1
{
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");

string name = req.Query["name"];
string ENVIROMENT = Environment.GetEnvironmentVariable("ConnectionStrings:Default");

string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;

string responseMessage = string.IsNullOrEmpty(name)
? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
: $" {ENVIROMENT}";

return new OkObjectResult(responseMessage);
}


}
The connection string is stored in the local.setting.json file in the function project. My question is how do I use this:
.UseSqlServer( configuration.GetConnectionString("Default"));
.UseSqlServer( configuration.GetConnectionString("Default"));
To read it? Do I understand correctly that I can store the access information there? I saw something about creating environment variables in azure and reading it with the function, not sure what's correct. Any advice would be appreciated
4 replies
CC#
Created by antimatter8189 on 2/26/2023 in #help
❔ One my my azure account not identified as one?
Hey there, I'm having an odd issue with my Azure account. I have two accounts linked to my Visual Studio, the main one which contains all my resources, and a dummy one which I created to check the issue. When I try to publish, I can switch between the two accounts, and the dummy one works just fine. However, the main one keeps telling me I need to sign in with an Azure account. I'm puzzled as to why this is happening. Can anyone provide any insight or suggestions for resolving the issue? I've already tried signing out of Visual Studio and signing back in with my main Azure account, but the problem persists. If anyone has any solutions, I would greatly appreciate your help. Thank you in advance!
2 replies