Alex
Alex
CC#
Created by Alex on 6/17/2024 in #help
What's wrong with my LINQ expression?
Hi! I'm trying to get data using LINQ expressions below. I use Sqlite
public async Task OnGetAsync()
{
var now = DateTimeOffset.Now;

LockedOutUsers =
await _userManager
.Users
.Where(u => u.LockoutEnd != null && u.LockoutEnd > now)
.OrderBy(u=>u.Email)
.ToListAsync();

OtherUsers = await _userManager
.Users.Where(u => u.LockoutEnd == null || u.LockoutEnd <= now)
.OrderBy(u => u.Email)
.ToListAsync();
}
public async Task OnGetAsync()
{
var now = DateTimeOffset.Now;

LockedOutUsers =
await _userManager
.Users
.Where(u => u.LockoutEnd != null && u.LockoutEnd > now)
.OrderBy(u=>u.Email)
.ToListAsync();

OtherUsers = await _userManager
.Users.Where(u => u.LockoutEnd == null || u.LockoutEnd <= now)
.OrderBy(u => u.Email)
.ToListAsync();
}
But I'm getting exception
InvalidOperationException: The LINQ expression 'DbSet<IdentityUser>() .Where(i => i.LockoutEnd != null && i.LockoutEnd.Value > __now_0)' could not be translated.
InvalidOperationException: The LINQ expression 'DbSet<IdentityUser>() .Where(i => i.LockoutEnd != null && i.LockoutEnd.Value > __now_0)' could not be translated.
56 replies
CC#
Created by Alex on 6/14/2024 in #help
✅ Malformed input: 321 is an invalid input length
I'm working with Asp.Net Core Identity. I use GeneratePasswordResetTokenAsync(user) to generate token and encode it with WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(token));. Next I decode encoded token with Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(encodedToken)) and get exception:
An unhandled exception occurred while processing the request.
FormatException: Malformed input: 321 is an invalid input length.
Microsoft.AspNetCore.WebUtilities.WebEncoders.GetNumBase64PaddingCharsToAddForDecode(int inputLength)
An unhandled exception occurred while processing the request.
FormatException: Malformed input: 321 is an invalid input length.
Microsoft.AspNetCore.WebUtilities.WebEncoders.GetNumBase64PaddingCharsToAddForDecode(int inputLength)
How can I fix my problem?
1 replies
CC#
Created by Alex on 5/19/2024 in #help
✅ Store data for the game
How can I efficiently store lines for the picture player draws? Each line contains color, line width and points (x,y). I have a group object that will have array of drawn linesбword players need to guess and state "drawing","choosing word", "idle". I need the data for players who join after the round started. I need the data between signalR calls
1 replies
CC#
Created by Alex on 5/16/2024 in #help
✅ SignalR client to client communication (chat)
Is it correct that I can't send messages from client to client directly using SignalR? Do I need to send http POST request to endpoint, then inside endpoint I get IHubContext and execute method ReceiveChatMessage? (Client code)

const onSubmit = (
values: SubmitMessageSchema,
reset: UseFormReset<SubmitMessageSchema>
) => {
// METHOD USERNAME MESSAGE
connection?.send("ReceiveChatMessage", "Alex", values.text);
reset();
};

const onSubmit = (
values: SubmitMessageSchema,
reset: UseFormReset<SubmitMessageSchema>
) => {
// METHOD USERNAME MESSAGE
connection?.send("ReceiveChatMessage", "Alex", values.text);
reset();
};
4 replies
CC#
Created by Alex on 5/15/2024 in #help
✅ what's the difference?
What's the difference between sending message to signalR endpoint directly and sending post to controller and execute it hubcinnection.sendasync method inside of it? I want to build game project based on signalr, one person draws the picture other guess what is it by typing it in chat. Can I use only one connection for both sending drawn pixels and chat messages? Should I send chat messages directly to signalR hub of to the post route of controller?
4 replies
CC#
Created by Alex on 5/12/2024 in #help
Storage for http request routes
In the method to search route I'll provide "Method" and "Path". Is there a better way to store routes that Dictionary<string,Dictionary<string,delegate>>?
1 replies
CC#
Created by Alex on 5/11/2024 in #help
How can I accept multiple clients?
I want to write my own http server using TCP and System.Net.Sockets. Here is my code:
using System.Net;
using System.Net.Sockets;
using System.Text;

const string ipAddress = "127.0.0.1";
const int port = 27015;

try
{

// create socket
Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);

// bind ip address

IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress),port);

listenSocket.Bind(ipEndPoint);

// Listen
listenSocket.Listen();

Console.WriteLine($"listening on http://{ipAddress}:{port}");

Socket acceptSocket = await listenSocket.AcceptAsync();



byte[] buffer = new byte[1024];
int bytesReceived = await acceptSocket.ReceiveAsync(buffer, SocketFlags.None);

string message = Encoding.UTF8.GetString(buffer, 0, bytesReceived);

Console.WriteLine(message);


string response = "HTTP/1.1 200 OK\r\nContent - Type: text/html\r\n\r\n{ \"msg\"=\"Hello world!\"}";


await acceptSocket.SendAsync(Encoding.UTF8.GetBytes(response, 0, response.Length));

acceptSocket.Close();

listenSocket.Close();
}
catch (Exception ex)
{
Console.WriteLine($"[{ex.GetType()}]: {ex.Message}");
}
using System.Net;
using System.Net.Sockets;
using System.Text;

const string ipAddress = "127.0.0.1";
const int port = 27015;

try
{

// create socket
Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);

// bind ip address

IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress),port);

listenSocket.Bind(ipEndPoint);

// Listen
listenSocket.Listen();

Console.WriteLine($"listening on http://{ipAddress}:{port}");

Socket acceptSocket = await listenSocket.AcceptAsync();



byte[] buffer = new byte[1024];
int bytesReceived = await acceptSocket.ReceiveAsync(buffer, SocketFlags.None);

string message = Encoding.UTF8.GetString(buffer, 0, bytesReceived);

Console.WriteLine(message);


string response = "HTTP/1.1 200 OK\r\nContent - Type: text/html\r\n\r\n{ \"msg\"=\"Hello world!\"}";


await acceptSocket.SendAsync(Encoding.UTF8.GetBytes(response, 0, response.Length));

acceptSocket.Close();

listenSocket.Close();
}
catch (Exception ex)
{
Console.WriteLine($"[{ex.GetType()}]: {ex.Message}");
}
How can I accept multiple sockets? Should I create new Thread for each socket (I'll add while loop later)? Also, should I store threads somewhere to finish them after I handled request? Maybe you can give any other advices on this topic
26 replies
CC#
Created by Alex on 5/8/2024 in #help
Serve SPA (React) in ASP.NET web API
No description
1 replies
CC#
Created by Alex on 5/7/2024 in #help
How to create first user (Admin)?
I have backend, users can create accounts, each account has role - admin or user. I want the first account to be Admin. Should I create it during database seeding or every time user register their account I check if it's first user and give him admin role? Or is there a better way? Aslo accounts must be verified to log in to it and only admin users can verify other user account.
8 replies
CC#
Created by Alex on 5/4/2024 in #help
✅ How to handle errors in services/controllers
Hi! I do most of work in services and then call the method in the controller. What's the proper way to handle errors that occur in service? I need return error to the frontend (the error model must be consistent). Is it fine to throw error in the services or is there a better way? Here is example of AccountService method
public async Task RegisterAsync(RegisterDto dto)
{
IdentityUser? foundUser = await _userManager.FindByEmailAsync(dto.Email);

if (foundUser != null)
{
throw new Exception($"Email '{dto.Email}' is already registered");
}

IdentityUser userToCreate = new IdentityUser
{
UserName = dto.Email,
Email = dto.Email
};

IdentityResult result = await _userManager.CreateAsync(userToCreate, dto.Password);

if (!result.Succeeded)
{
throw new Exception($"Failed to create user:{string.Join(',', result.Errors.Select(e => e.Description))}");
}
}
public async Task RegisterAsync(RegisterDto dto)
{
IdentityUser? foundUser = await _userManager.FindByEmailAsync(dto.Email);

if (foundUser != null)
{
throw new Exception($"Email '{dto.Email}' is already registered");
}

IdentityUser userToCreate = new IdentityUser
{
UserName = dto.Email,
Email = dto.Email
};

IdentityResult result = await _userManager.CreateAsync(userToCreate, dto.Password);

if (!result.Succeeded)
{
throw new Exception($"Failed to create user:{string.Join(',', result.Errors.Select(e => e.Description))}");
}
}
10 replies
CC#
Created by Alex on 5/4/2024 in #help
✅ redirect url is not passed to request
No description
1 replies
CC#
Created by Alex on 5/3/2024 in #help
✅ Challenge does not redirect
[HttpPost("sign-in/external")]
public IActionResult SignInExternal([FromQuery] string provider ="Google", [FromQuery] string returnUrl = "https://localhost:8080/api/identity/sign-in/google")
{
AuthenticationProperties properties = _identityService.SignInExternal(provider,returnUrl);

return Challenge(properties,provider);
}
[HttpPost("sign-in/external")]
public IActionResult SignInExternal([FromQuery] string provider ="Google", [FromQuery] string returnUrl = "https://localhost:8080/api/identity/sign-in/google")
{
AuthenticationProperties properties = _identityService.SignInExternal(provider,returnUrl);

return Challenge(properties,provider);
}
What can be the reason?
4 replies
CC#
Created by Alex on 5/3/2024 in #help
✅ Google External sign in using Identity
I want to learn how to implement a google external sign-in route (and Identity in general) in my ASP.NET Web API but I can't find any recent tutorial on that topic. Microsoft's official tutorial is for RazorPages only and tells you to add AddAuthentication().AddGoogle() and everything should work. I want to create it for Web API because I need it for the React front end. I found a few tutorials but they are 3-5 years old. Can you suggest any tutorials on this topic or for Identity in Web API in general? Also, I used it about 2 years ago and I had to create routes like register and login by myself using userManager and signInManager etc, now the tutorial suggests using MapIdentityApi which serves pre-made routes which I can't modify. Is it a new way to use Identity or it's just made for simplicity in tutorial only?
4 replies
CC#
Created by Alex on 4/30/2024 in #help
CRUD for complex objects
No description
16 replies
CC#
Created by Alex on 4/27/2024 in #help
✅ Run PuppeteerSharp in Docker Container
I have an endpoint that creates PDFs using PuppeteerSharp. I work fine locally because it can automatically download Chromium. The opposite in the Docker Container, it tells me that no executable chromium found. Is there a way to pre download?
FROM mcr.microsoft.com/dotnet/sdk:8.0 as build
WORKDIR /App

COPY . ./

RUN dotnet restore
RUN dotnet publish -c Release -o out

FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /App
COPY --from=build /App/out .
ENTRYPOINT ["dotnet", "Vocabify.API.dll"]
FROM mcr.microsoft.com/dotnet/sdk:8.0 as build
WORKDIR /App

COPY . ./

RUN dotnet restore
RUN dotnet publish -c Release -o out

FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /App
COPY --from=build /App/out .
ENTRYPOINT ["dotnet", "Vocabify.API.dll"]
17 replies
CC#
Created by Alex on 4/27/2024 in #help
Help with API structure
I want to create modular API structure https://timdeschryver.dev/blog/maybe-its-time-to-rethink-our-project-structure-with-dot-net-6#a-domain-driven-api like in this article. I split solution into .API and .Modules project. The problem is that I'm using MVC in my project and I don't how to apply it for MVC. For example where should I create controllers? In API project or Modules project?
Vocabify.API/
- Controllers/
Controller1.cs
Vocabify.Modules/
IModule.cs
- Module1
- Module2
Vocabify.API/
- Controllers/
Controller1.cs
Vocabify.Modules/
IModule.cs
- Module1
- Module2
61 replies
CC#
Created by Alex on 4/22/2024 in #help
✅ where DSA can be applied?
I have a task to measure performance of different data structures, for example tree and linked list. What kind of project can be done using different types of data structures, but it shouldn't be abstract, need to have application in real world ?
5 replies
CC#
Created by Alex on 4/19/2024 in #help
What's is good ASP.NET web API project structure
Can you recommend good project structure for small or medium web api project? Maybe you have a link to an example. I read about DDD or "Clean Architecture", but it looks over complicated. I was thinking about modular, but should I split modules is different projects or keep them in one separate?
55 replies
CC#
Created by Alex on 4/13/2024 in #help
Static property override
I have a base class BaseOptions and it has name value, that I will override in each child class. Base Class
public (class/interface) BaseOptions
{
string Name
}
public (class/interface) BaseOptions
{
string Name
}
Child Class
public class ApplicationOptions:BaseOptions
{
public required string ClientBaseUrl { get; set; }
// override string Name
}
public class ApplicationOptions:BaseOptions
{
public required string ClientBaseUrl { get; set; }
// override string Name
}
Usage
builder.Services.Configure<ApplicationOptions>(builder.Configuration.GetSection(ApplicationOptions.Name));
builder.Services.Configure<ApplicationOptions>(builder.Configuration.GetSection(ApplicationOptions.Name));
What should I use to create structure like above?
26 replies
CC#
Created by Alex on 4/8/2024 in #help
Redis.OM Indexes are dropped automatically
I create index using Redis.OM , after some time they are deleted for no reason
Provider.Connection.CreateIndexAsync(typeof(T));
Provider.Connection.CreateIndexAsync(typeof(T));
and I'm getting error
[name]-idx: no such index\nFailed on FT.SEARCH station-idx * LIMIT 0 100
[name]-idx: no such index\nFailed on FT.SEARCH station-idx * LIMIT 0 100
18 replies