S-IERRA
S-IERRA
CC#
Created by S-IERRA on 2/14/2024 in #help
ASP.Net IActionResult always returns Ok
I have the following method inside of a service, I call this method from a controller Where its suppsoe to return 404 not found it enters the return statement and jumps to the last line of the method (Return Ok) This seems to happen on all methods, possibly there is a better way of returning values from services?
public async Task<IActionResult> DeleteServer(int id)
{
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();

if (await dbContext.Servers.FirstOrDefaultAsync(x => x.Id == id) is not { } server)
return new NotFoundObjectResult(new ErrorResponse(RestErrors.FailedToFind($"server{id}")));

dbContext.Servers.Remove(server);
await dbContext.SaveChangesAsync();

return new OkResult();
}
public async Task<IActionResult> DeleteServer(int id)
{
await using var dbContext = await _dbContextFactory.CreateDbContextAsync();

if (await dbContext.Servers.FirstOrDefaultAsync(x => x.Id == id) is not { } server)
return new NotFoundObjectResult(new ErrorResponse(RestErrors.FailedToFind($"server{id}")));

dbContext.Servers.Remove(server);
await dbContext.SaveChangesAsync();

return new OkResult();
}
This is how I call this method
[HttpDelete("{id:int}/delete")]
public async Task<IActionResult> DeleteServer(int id)
{
return await _serverService.DeleteServer(id);
}
[HttpDelete("{id:int}/delete")]
public async Task<IActionResult> DeleteServer(int id)
{
return await _serverService.DeleteServer(id);
}
82 replies
CC#
Created by S-IERRA on 9/24/2023 in #help
❔ Sockets, SendTo is erroring
A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied. With my setup, the socket is connected in a different class but I am trying to send a message to that socket via its endpoint where I get an error, is that possible or do I have to use the socket class its self?
public static async Task SendToEndPointAsync(IPEndPoint target, WebSocketOpcodes webSocketOpCode, WebSocketEvents? eventType = null, string? dataSerialized = null)
{
try
{
var socketMessage = new WebSocketMessage(webSocketOpCode, dataSerialized, eventType, null);

string messageSerialized = JsonSerializer.Serialize(socketMessage);

byte[] dataCompressed = Encoding.UTF8.GetBytes(messageSerialized); /

await Listener.SendToAsync(dataCompressed, SocketFlags.None, target);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public static async Task SendToEndPointAsync(IPEndPoint target, WebSocketOpcodes webSocketOpCode, WebSocketEvents? eventType = null, string? dataSerialized = null)
{
try
{
var socketMessage = new WebSocketMessage(webSocketOpCode, dataSerialized, eventType, null);

string messageSerialized = JsonSerializer.Serialize(socketMessage);

byte[] dataCompressed = Encoding.UTF8.GetBytes(messageSerialized); /

await Listener.SendToAsync(dataCompressed, SocketFlags.None, target);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
37 replies
CC#
Created by S-IERRA on 9/11/2023 in #help
❔ EFC Is not loading collection properly
120 replies
CC#
Created by S-IERRA on 9/9/2023 in #help
❔ Entityframework model
I have the following models in EFC, I need the server member to share the id of user Id as I do not want to make a new Id for it entierly (if thats even possible) tho i'm getting errors saying the code needs a primary key when I do define a key
public class ChatServerMember : IEntityTypeConfiguration<ChatServerMember>
{
public required Guid UserId { get; set; }
public ChatUser User { get; set; }

public required Guid ServerId { get; set; }
public ChatServer Server { get; set; }

public ChatPermissions Permissions { get; set; }

public virtual ICollection<ChatServerRole> Roles { get; set; } = new HashSet<ChatServerRole>();

public void Configure(EntityTypeBuilder<ChatServerMember> builder)
{
builder.ToTable("ServerMembers");

builder.HasKey(x => new { x.UserId, x.ServerId });

builder.HasOne(x => x.Server)
.WithMany(x => x.Members)
.HasForeignKey(x => x.ServerId)
.OnDelete(DeleteBehavior.SetNull);
}
}
public class ChatServerMember : IEntityTypeConfiguration<ChatServerMember>
{
public required Guid UserId { get; set; }
public ChatUser User { get; set; }

public required Guid ServerId { get; set; }
public ChatServer Server { get; set; }

public ChatPermissions Permissions { get; set; }

public virtual ICollection<ChatServerRole> Roles { get; set; } = new HashSet<ChatServerRole>();

public void Configure(EntityTypeBuilder<ChatServerMember> builder)
{
builder.ToTable("ServerMembers");

builder.HasKey(x => new { x.UserId, x.ServerId });

builder.HasOne(x => x.Server)
.WithMany(x => x.Members)
.HasForeignKey(x => x.ServerId)
.OnDelete(DeleteBehavior.SetNull);
}
}
26 replies
CC#
Created by S-IERRA on 9/1/2023 in #help
❔ EntityFramework Code cleanup
I have lots of controllers like this, is there anyway I could clean this up? for one I don't want to be calling the firstordefaultasync each time I have an ID parameter possibly there is somew ay to implicitly convert it while carrying context for performance sake? Also I was thinking of moving the logic to the Logic layer But I'm not sure how I'd do validation there and return it, for example. if a user has missing permissions
return Unauthorized();
return Unauthorized();
[HttpPost("{serverId:guid}/view-logs")]
public async Task<IActionResult> ViewLogs([FromClaim(ChatClaims.UserId)] Guid userId, Guid serverId)
{
await using var context = ContextFactory.CreateDbContext();

if (await context.Users.FirstOrDefaultAsync(x => x.Id == userId) is not { } user)
return Unauthorized();

if (await context.Servers.FirstOrDefaultAsync(x => x.Id == serverId) is not { } server)
return Unauthorized();

context.Servers.Remove(server);

return Ok();
}

[HttpPost("{serverId:guid}/create-invite")]
public async Task<IActionResult> CreateInvite([FromClaim(ChatClaims.UserId)] Guid userId, Guid serverId)
{
return Ok();
}
[HttpPost("{serverId:guid}/view-logs")]
public async Task<IActionResult> ViewLogs([FromClaim(ChatClaims.UserId)] Guid userId, Guid serverId)
{
await using var context = ContextFactory.CreateDbContext();

if (await context.Users.FirstOrDefaultAsync(x => x.Id == userId) is not { } user)
return Unauthorized();

if (await context.Servers.FirstOrDefaultAsync(x => x.Id == serverId) is not { } server)
return Unauthorized();

context.Servers.Remove(server);

return Ok();
}

[HttpPost("{serverId:guid}/create-invite")]
public async Task<IActionResult> CreateInvite([FromClaim(ChatClaims.UserId)] Guid userId, Guid serverId)
{
return Ok();
}
25 replies
CC#
Created by S-IERRA on 8/30/2023 in #help
❔ Cors Policy Error
When ever my front-end tries to communicate with my back-end I receive this error, any ideas why? https://cdn.discordapp.com/attachments/1136302991666843680/1146527808072454144/image.png
72 replies
CC#
Created by S-IERRA on 8/30/2023 in #help
❔ Problem setting up ASP.NET on Linux
Hi, I'm trying to setup ASP on linux but I'm getting erros like this https://cdn.discordapp.com/attachments/679791684548296735/1146446137662914590/image.png
35 replies
CC#
Created by S-IERRA on 8/21/2023 in #help
❔ ASP.NET always validates invalid JWT
I have a custom configuration for Asp.net where the JWT Token is stored in an http-only cookie, because of this there is 1 method in specific that is always returning 200 no matter if there is no actual JWT attached
public static void RegisterAuthorization(this IServiceCollection serviceCollection, IConfiguration configuration)
{
var jwtConfig = configuration.GetSection("Jwt").Get<JwtConfig>()!;
serviceCollection.Configure<JwtConfig>(configuration.GetSection("Jwt"));

serviceCollection.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = jwtConfig.Audience,
ValidIssuer = jwtConfig.Issuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.Key))
};

options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
context.Token = context.Request.Cookies["JwtToken"];

return Task.CompletedTask;
}
};
});

serviceCollection.AddAuthorization(options =>
{
options.AddPolicy(NumixAuthPolicy.Admin.ToString(), policy =>
policy.RequireClaim(ClaimTypes.Role, NumixRole.Administrator.ToString()));
});

serviceCollection.AddScoped(typeof(IAuthenticatorService), typeof(Authenticate));
}
public static void RegisterAuthorization(this IServiceCollection serviceCollection, IConfiguration configuration)
{
var jwtConfig = configuration.GetSection("Jwt").Get<JwtConfig>()!;
serviceCollection.Configure<JwtConfig>(configuration.GetSection("Jwt"));

serviceCollection.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = jwtConfig.Audience,
ValidIssuer = jwtConfig.Issuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.Key))
};

options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
context.Token = context.Request.Cookies["JwtToken"];

return Task.CompletedTask;
}
};
});

serviceCollection.AddAuthorization(options =>
{
options.AddPolicy(NumixAuthPolicy.Admin.ToString(), policy =>
policy.RequireClaim(ClaimTypes.Role, NumixRole.Administrator.ToString()));
});

serviceCollection.AddScoped(typeof(IAuthenticatorService), typeof(Authenticate));
}
76 replies
CC#
Created by S-IERRA on 8/19/2023 in #help
❔ JWT Storage location
Hi I'd like to ask where JWTs should be stored, my backend returns a JWT through the API and also sets an http-only cookie, but I'm not sure what to do with this from the front end as ASP requires an Authorization header and http only cookies can't be accessed from the front-end any ideas? This is for most part what I do
NumixAuthenticated jwtToken = _authenticatorService.GenerateToken(jwtUser);
string jwtTokenJson = JsonSerializer.Serialize(jwtToken, JsonHelper.JsonSerializerOptions);

var options = new CookieOptions
{
HttpOnly = true,
};

Response.Cookies.Append("Numix", jwtTokenJson, options);

return Ok(jwtTokenJson);

NumixAuthenticated jwtToken = _authenticatorService.GenerateToken(jwtUser);
string jwtTokenJson = JsonSerializer.Serialize(jwtToken, JsonHelper.JsonSerializerOptions);

var options = new CookieOptions
{
HttpOnly = true,
};

Response.Cookies.Append("Numix", jwtTokenJson, options);

return Ok(jwtTokenJson);

25 replies
CC#
Created by S-IERRA on 8/6/2023 in #help
❔ SmptClient invalid response to the EHLO command.
I have 2 versions of this project one is one console which works perfectly well the other one is on Asp.net which is always receiving "The server returned an invalid response to the EHLO command." The code is pretty much identical across the both of them I assume it could be asp blocking the request? Asp.net src (not working)
private async Task<bool> SendAsync(string recipientEmail, string subject, string body)
{
const string senderEmail = "removed"; // Your Gmail email address
const string senderPassword = "removed"; // Your application-specific password

SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential(senderEmail, senderPassword);

var mailMessage = new MailMessage(senderEmail, "[email protected]", "test", "test2");
mailMessage.IsBodyHtml = true;

await smtpClient.SendMailAsync(mailMessage);
}
private async Task<bool> SendAsync(string recipientEmail, string subject, string body)
{
const string senderEmail = "removed"; // Your Gmail email address
const string senderPassword = "removed"; // Your application-specific password

SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential(senderEmail, senderPassword);

var mailMessage = new MailMessage(senderEmail, "[email protected]", "test", "test2");
mailMessage.IsBodyHtml = true;

await smtpClient.SendMailAsync(mailMessage);
}
Console app Src (working)
public class MailService
{
private const string SenderEmail = "removed"; // Your Gmail email address
private const string SenderPassword = "removed"; // Your application-specific password

private readonly SmtpClient _smtpClient = new SmtpClient("smtp.gmail.com", 587);

public MailService()
{
_smtpClient.EnableSsl = true;
_smtpClient.UseDefaultCredentials = false;
_smtpClient.Credentials = new NetworkCredential(SenderEmail, SenderPassword);
}

public async Task<bool> SendAsync(string recipientEmail, string subject, string body)
{
var mailMessage = new MailMessage(SenderEmail, recipientEmail, subject, body);
mailMessage.IsBodyHtml = true;

await _smtpClient.SendMailAsync(mailMessage);
}
}
public class MailService
{
private const string SenderEmail = "removed"; // Your Gmail email address
private const string SenderPassword = "removed"; // Your application-specific password

private readonly SmtpClient _smtpClient = new SmtpClient("smtp.gmail.com", 587);

public MailService()
{
_smtpClient.EnableSsl = true;
_smtpClient.UseDefaultCredentials = false;
_smtpClient.Credentials = new NetworkCredential(SenderEmail, SenderPassword);
}

public async Task<bool> SendAsync(string recipientEmail, string subject, string body)
{
var mailMessage = new MailMessage(SenderEmail, recipientEmail, subject, body);
mailMessage.IsBodyHtml = true;

await _smtpClient.SendMailAsync(mailMessage);
}
}
3 replies