İrşat
İrşat
CC#
Created by İrşat on 9/27/2023 in #help
❔ .NET 7 in Cpanel
Does Plesk 10 support .NET 7? Probably not. Can I use dotnet publish as linux and use Cpanel? (context: I bought a hosting with all the ssl, domain in it for a nice price. The saleswoman said yes it supports .NET 7. I noticed it only has Plesk 10, Cpanel and DirectAdmin smh)
2 replies
CC#
Created by İrşat on 9/25/2023 in #help
❔ .NET 7 + React deployment concept?
I am having a hard time understanding the google cloud deployment method. Let's say I created an app with dotnet new react, now I have an API and inside the folder there is ClientApp. I need a docker image too. But here is the part I have no idea about; How do I deploy them together? Or do I host them seperately? How can I have them both in the same url? Do I need docker image for react app? It's bundled so I don't think I need one. If yes, both of them get the same image? So many questions, I just need to understand the concept. edit: dotnet publish --os linux --arch x64 -p:PublishProfile=DefaultContainer & npm run build I also used these. I just saw ClientApp as wwwroot inside bin/../publish
3 replies
CC#
Created by İrşat on 9/15/2023 in #help
❔ transaction.Rollback(); vs SaveChanges; at the end
using (var transaction = _db.Database.BeginTransaction())
{
try
{
// Remove all existing testimonials
_db.Testimonials.RemoveRange(_db.Testimonials);

// Add new testimonials
_db.Testimonials.AddRange(newTestimonials);

await _db.SaveChangesAsync();

// If everything is successful, commit the transaction
transaction.Commit();

return Ok(new { message = "Success" });
}
catch (Exception)
{
// If an exception occurs, roll back the transaction
transaction.Rollback();
return StatusCode(500, new { message = "Error" });
}
}
using (var transaction = _db.Database.BeginTransaction())
{
try
{
// Remove all existing testimonials
_db.Testimonials.RemoveRange(_db.Testimonials);

// Add new testimonials
_db.Testimonials.AddRange(newTestimonials);

await _db.SaveChangesAsync();

// If everything is successful, commit the transaction
transaction.Commit();

return Ok(new { message = "Success" });
}
catch (Exception)
{
// If an exception occurs, roll back the transaction
transaction.Rollback();
return StatusCode(500, new { message = "Error" });
}
}
Would the records be safe in case AddRange fails if I don't use RollBack?
6 replies
CC#
Created by İrşat on 2/20/2023 in #help
✅ dotnet new react - with mvc?
63 replies
CC#
Created by İrşat on 2/15/2023 in #help
✅ End point can't take byte[] from HTTP Request. Only int[].
//model
public int[]? coverImage { get; set; }
//model
public int[]? coverImage { get; set; }
//In a function
var coverimg_file = coverImg_input.files;
if (coverimg_file && coverimg_file[0]) {
var file = coverimg_file[0];
formData.coverImage = await ImageToByteArray(file);
//coverImage!: Number[] | null;
//ArrayBuffer type didn't work, idk i didn't dig in too much
}

async function ImageToByteArray(file: File): Promise<Number[] | null> {
return new Promise((resolve) => {
const reader = new FileReader()
reader.onloadend = () => {
var data = reader.result as ArrayBuffer | null;
if (data != null) {
return resolve([...new Uint8Array(data)]);
}
else {
return resolve(null);
}
};
reader.readAsArrayBuffer(file);
})
}

//Fetch init;
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
}
//In a function
var coverimg_file = coverImg_input.files;
if (coverimg_file && coverimg_file[0]) {
var file = coverimg_file[0];
formData.coverImage = await ImageToByteArray(file);
//coverImage!: Number[] | null;
//ArrayBuffer type didn't work, idk i didn't dig in too much
}

async function ImageToByteArray(file: File): Promise<Number[] | null> {
return new Promise((resolve) => {
const reader = new FileReader()
reader.onloadend = () => {
var data = reader.result as ArrayBuffer | null;
if (data != null) {
return resolve([...new Uint8Array(data)]);
}
else {
return resolve(null);
}
};
reader.readAsArrayBuffer(file);
})
}

//Fetch init;
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
}
If I use byte[] type, it gives me null.
50 replies
CC#
Created by İrşat on 1/10/2023 in #help
❔ how to use Docker for 2 apps in a project
MyProject
> WebApp
> WebApi
MyProject.sln
MyProject
> WebApp
> WebApi
MyProject.sln
-They both require .NET 6.0.404 and Entity Framework. -I use VS CODE. -WebApp and WebApi have different packages inside them. Afaik they are inside the projects so they don't require a reference in the Docker Image, correct me if I am wrong. -I use Git. Not sure if it affects. So where do I start creating an image? (+ should I use docker in the development process?)
3 replies
CC#
Created by İrşat on 12/27/2022 in #help
✅ (Linq) Assigning value in OrderBy lambda function
int hrVoteResult = 0;
comment.highlightedReply = await _mapper.ProjectTo<ReplyDtoRead_2>(_db.Replies
.Where(r => r.deletedStatus.body == "Default" &&
r.commentId == comment.id)
.OrderByDescending(r =>
{
hrVoteResult = r.Votes.Sum(v => v.body == true ? 1 : -1;
return hrVoteResult;
})
.Take(1))
.FirstOrDefaultAsync();
int hrVoteResult = 0;
comment.highlightedReply = await _mapper.ProjectTo<ReplyDtoRead_2>(_db.Replies
.Where(r => r.deletedStatus.body == "Default" &&
r.commentId == comment.id)
.OrderByDescending(r =>
{
hrVoteResult = r.Votes.Sum(v => v.body == true ? 1 : -1;
return hrVoteResult;
})
.Take(1))
.FirstOrDefaultAsync();
Error: A lambda expression must have an expression body to be converted to an expression tree. This works fine btw; .OrderByDescending(r => r.Votes.Sum(v => v.body == true ? 1 : -1)
35 replies
CC#
Created by İrşat on 12/26/2022 in #help
✅ EF two Select in a query problem when using ToList().
var monthsTopPosts = _db.Votes
.Where(v =>
v.targetPostId != null &&
v.targetPost!.isPublished == true &&
v.targetPost!.deletedStatus != null &&
v.targetPost!.deletedStatus.body == "Default" &&
v.targetPost!.publishDate > DateTime.Now.AddDays(-30))
.GroupBy(v => v.targetPostId)
.Select(g => new
{
post = g.First().targetPost,
karma = g.Sum(v => v.body == true ? 1 : -1)
})
.OrderByDescending(k => k.karma)
.Take(1)
.ToList()
.Select(x => x.post)
.ToList();
var monthsTopPosts = _db.Votes
.Where(v =>
v.targetPostId != null &&
v.targetPost!.isPublished == true &&
v.targetPost!.deletedStatus != null &&
v.targetPost!.deletedStatus.body == "Default" &&
v.targetPost!.publishDate > DateTime.Now.AddDays(-30))
.GroupBy(v => v.targetPostId)
.Select(g => new
{
post = g.First().targetPost,
karma = g.Sum(v => v.body == true ? 1 : -1)
})
.OrderByDescending(k => k.karma)
.Take(1)
.ToList()
.Select(x => x.post)
.ToList();
I want to reduce two ToList() to one. But it gives me error.
System.InvalidOperationException: The LINQ expression 'ProjectionBindingExpression: 0' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
27 replies
CC#
Created by İrşat on 12/25/2022 in #help
✅ Ordering IQueryable by the indexes of another list
List<int> savedPostIds = await _db.SavedPosts
.Where(a => a.account.username == targetUsername)
.OrderByDescending(a => a.saveDate)
.Select(x => x.targetPostId)
.ToListAsync();

var posts = await _mapper.ProjectTo<PostDtoRead_1>(_db.Posts
.Where(p => savedPostIds.Contains(p.id))
.OrderBy(p => savedPostIds.IndexOf(p.id)))
.ToListAsync();
List<int> savedPostIds = await _db.SavedPosts
.Where(a => a.account.username == targetUsername)
.OrderByDescending(a => a.saveDate)
.Select(x => x.targetPostId)
.ToListAsync();

var posts = await _mapper.ProjectTo<PostDtoRead_1>(_db.Posts
.Where(p => savedPostIds.Contains(p.id))
.OrderBy(p => savedPostIds.IndexOf(p.id)))
.ToListAsync();
IndexOf method doesn't work on IQueryable it seems.
posts = posts.OrderBy(p => savedPostIds.IndexOf(p.id)).ToList();
posts = posts.OrderBy(p => savedPostIds.IndexOf(p.id)).ToList();
I can do that but that makes it look bad, idk. Is it even good practice?
38 replies
CC#
Created by İrşat on 12/7/2022 in #help
✅ Upgrading Javascript to Typescript in MVC project
I globally installed npm and typescript. Then created a tsconfig.json in my project. But I have no idea what to do after that.
"include": ["TypeScript"],
"compilerOptions": {
"outDir": "./wwwroot/js",
"include": ["TypeScript"],
"compilerOptions": {
"outDir": "./wwwroot/js",
I am trying to put my .ts files in TypeScript folder directly under the App.Web. Both TypeScript folder and tsconfig.json are right under App.Web. (I have 2 apps in one project. App.Web and App.Api)
App.Web
MVC structure
TypeScript
firsttry.ts
tsconfig.json
App.Api
App.Web
MVC structure
TypeScript
firsttry.ts
tsconfig.json
App.Api
Installing typescript in App.Web was a torture. I gave up and installed it globally.
41 replies
CC#
Created by İrşat on 12/3/2022 in #help
❔ How do we download an image from url in NET 6?
When I search it on google, all the answers are outdated.
var res = await _httpClient.GetAsync(picUrl);
byte[] bytes = await res.Content.ReadAsByteArrayAsync();
var res = await _httpClient.GetAsync(picUrl);
byte[] bytes = await res.Content.ReadAsByteArrayAsync();
Then I need to put it into my wwwroot folder too.
75 replies
CC#
Created by İrşat on 10/31/2022 in #help
Calculating post contents without fetching
Stopwatch elapsedTimeForExtras = new Stopwatch();
elapsedTimeForExtras.Start();
foreach (PostDtoRead_1 post in posts_onepage)
{
//remove if the chapters are not published
//Maybe I can fix this from the root later
if (post.chapters != null && post.chapters.Count() > 0)
post.chapters = post.chapters.Where(c => c.IsPublished == true).ToList();

//Get comment and reply count
var commentIds = _db.Comments
.Where(x => x.targetPostId == post.id &&
x.deletedStatus.body == "Default")
.Select(x => x.id);
var replyIds = _db.Replies
.Where(x => commentIds.Contains(x.commentId ?? 0) &&
x.deletedStatus.body == "Default")
.Select(x => x.id);
post.comRepLength = commentIds.Count() + replyIds.Count();

//Get the sum of words in chapters of the post
char[] wordSeparator = new char[] {' ', '\r', '\n' };
var chbodyList = _db.Chapters
.Where(x => x.postId == post.id &&
x.deletedStatus.body == "Default" &&
x.isPublished == true)
.Select(x => x.body);
foreach(string? chbody in chbodyList){
post.wordsLength += chbody != null
? chbody.Split(wordSeparator, StringSplitOptions.RemoveEmptyEntries).Length : 0;
}

//check vote by user
if (userId != null)
{
Vote? checkVoteByUser = await _db.Votes.SingleOrDefaultAsync(v =>
v.accountId == userId &&
v.targetPostId == post.id);
if (checkVoteByUser != null)
post.VotedByUser = checkVoteByUser.body;
}
}
elapsedTimeForExtras.Stop();
Stopwatch elapsedTimeForExtras = new Stopwatch();
elapsedTimeForExtras.Start();
foreach (PostDtoRead_1 post in posts_onepage)
{
//remove if the chapters are not published
//Maybe I can fix this from the root later
if (post.chapters != null && post.chapters.Count() > 0)
post.chapters = post.chapters.Where(c => c.IsPublished == true).ToList();

//Get comment and reply count
var commentIds = _db.Comments
.Where(x => x.targetPostId == post.id &&
x.deletedStatus.body == "Default")
.Select(x => x.id);
var replyIds = _db.Replies
.Where(x => commentIds.Contains(x.commentId ?? 0) &&
x.deletedStatus.body == "Default")
.Select(x => x.id);
post.comRepLength = commentIds.Count() + replyIds.Count();

//Get the sum of words in chapters of the post
char[] wordSeparator = new char[] {' ', '\r', '\n' };
var chbodyList = _db.Chapters
.Where(x => x.postId == post.id &&
x.deletedStatus.body == "Default" &&
x.isPublished == true)
.Select(x => x.body);
foreach(string? chbody in chbodyList){
post.wordsLength += chbody != null
? chbody.Split(wordSeparator, StringSplitOptions.RemoveEmptyEntries).Length : 0;
}

//check vote by user
if (userId != null)
{
Vote? checkVoteByUser = await _db.Votes.SingleOrDefaultAsync(v =>
v.accountId == userId &&
v.targetPostId == post.id);
if (checkVoteByUser != null)
post.VotedByUser = checkVoteByUser.body;
}
}
elapsedTimeForExtras.Stop();
This alone takes more than 100ms. I wonder if it's optimized. With the rest, it's around 150-200ms. There are barelly any text in chapters and comments. So I am confused why it's that long. I tested by commenting the counting reply. It's the one with 100ms.
3 replies
CC#
Created by İrşat on 10/26/2022 in #help
SameSite problem - google cookies
Indicate whether to send a cookie in a cross-site request by specifying its SameSite attribute I still get this warning even after I wrote this in program.cs.
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromHours(4);
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
})
.AddGoogle(GoogleDefaults.AuthenticationScheme, googleOptions =>
{
googleOptions.ClientId = configuration["Authentication:Google:ClientId"];
googleOptions.ClientSecret = configuration["Authentication:Google:ClientSecret"];
googleOptions.CorrelationCookie.SameSite = SameSiteMode.None;
googleOptions.CorrelationCookie.SecurePolicy = CookieSecurePolicy.Always;
});
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromHours(4);
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
})
.AddGoogle(GoogleDefaults.AuthenticationScheme, googleOptions =>
{
googleOptions.ClientId = configuration["Authentication:Google:ClientId"];
googleOptions.ClientSecret = configuration["Authentication:Google:ClientSecret"];
googleOptions.CorrelationCookie.SameSite = SameSiteMode.None;
googleOptions.CorrelationCookie.SecurePolicy = CookieSecurePolicy.Always;
});
5 replies
CC#
Created by İrşat on 10/24/2022 in #help
Creating a return to page button
I have a post info page and posts page. Now posts page can have many filters, page number and stuff, I don't want to lose them. Just like when I click the built-in previous page icon, it should return to the posts page. I need to go back to the posts page with a custom button because I can go further deep and return to post info page which renders built-in back icon useless. The problem is how will I store this posts url information. It's harder because I can return to post info page from the post's chapters.
2 replies
CC#
Created by İrşat on 10/13/2022 in #help
I can't get fetch body as plain string [Answered]
public async Task<JsonResult> GoogleSignin([FromBody] string googleToken)
public async Task<JsonResult> GoogleSignin([FromBody] string googleToken)
await fetch("/Auth/GoogleSignin", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: response.credential
})
await fetch("/Auth/GoogleSignin", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: response.credential
})
Normal text instead of response.credential also doesn't work. I used json stringfy, object etc, didn't work
5 replies
CC#
Created by İrşat on 10/12/2022 in #help
How to process IActionResult Ok(value) return in back end. [Answered]
string url = "Read/GetPost?postid=" + postid;
var apiResponse = await _httpClient.GetFromJsonAsync<>(url);
string url = "Read/GetPost?postid=" + postid;
var apiResponse = await _httpClient.GetFromJsonAsync<>(url);
What should I write inside the getfromjsonasync?
9 replies
CC#
Created by İrşat on 10/10/2022 in #help
Environmental Variables in VS 2022 [Answered]
{
"profiles": {
"Library.Dependency": {
"commandName": "Project",
"environmentVariables": {
"MyLibs": "C:\\MyProject",
"Configuration": "Release"
}
}
}
}
{
"profiles": {
"Library.Dependency": {
"commandName": "Project",
"environmentVariables": {
"MyLibs": "C:\\MyProject",
"Configuration": "Release"
}
}
}
}
I am trying to get those environmental variables and write them here;
<PropertyGroup>
<OutputPath>$(MyLibs)\\$(Configuration)</OutputPath>
<Company>Software</Company>
<Authors>Software</Authors>
</PropertyGroup>
<PropertyGroup>
<OutputPath>$(MyLibs)\\$(Configuration)</OutputPath>
<Company>Software</Company>
<Authors>Software</Authors>
</PropertyGroup>
I realized that VS 2022 doesn't support this. So I experimented and used windows environmental variables instead. Mission accomplished unsuccessfully.
<OutputPath>%MyLibs%</OutputPath>
<OutputPath>%MyLibs%</OutputPath>
It finally shows something else than just C:\Debug. It doesn't work regardless. How do I do this normally? Oh and it would be nice if I could reach this damn thing from the entire project. There is one main project and some dependencies. All uses these.
2 replies
CC#
Created by İrşat on 10/4/2022 in #help
HttpRequestException Error Handling
It says the target actively refused it. It's because I didn't launch my API. Therefore it cannot request something and gives me this error. If we put try catch aside for a minute, is there a nice way to just skip these codes if it refuses? I will send empty lists to the client and just say "Sorry, we are having some technical issues." or something.
14 replies
CC#
Created by İrşat on 9/30/2022 in #help
Check if user already voted this post or comment [Answered]
I want to fill the like/dislike buttons with color if they are already voted by the user. Which one would be faster and more economic; -Fetching the votes of the parent post/comment from the start, then checking if this user's id is there or... -Another request to the api to check if user has a record already with that post's id in votes table.
54 replies
CC#
Created by İrşat on 9/27/2022 in #help
EF sets a property out of nowhere [Solved] [Answered]
public int RepliesLength { get; set; } = 0;
public int RepliesCount { get; set; } = 0;

public CommentDtoRead_2(ICollection<VoteDto>? Votes, ICollection<ReplyDtoRead_1>? Replies)
{
if(Replies != null && Replies.Count > 0) {
this.RepliesLength = Replies.Count(r => r.DeletedStatus!.Body == "Default");
this.RepliesCount = Replies.Count(r => r.DeletedStatus!.Body == "Default");
}
}
public int RepliesLength { get; set; } = 0;
public int RepliesCount { get; set; } = 0;

public CommentDtoRead_2(ICollection<VoteDto>? Votes, ICollection<ReplyDtoRead_1>? Replies)
{
if(Replies != null && Replies.Count > 0) {
this.RepliesLength = Replies.Count(r => r.DeletedStatus!.Body == "Default");
this.RepliesCount = Replies.Count(r => r.DeletedStatus!.Body == "Default");
}
}
I have a model with this constructor. Basically, I get the amount of replies which are not deleted through Count. Total is 5 and 3 of them are not deleted. Literally the same codes. But at the end, RepliesCount returns 5 and RepliesLength returns 3. RepliesLength can have any name. But when I use the name "RepliesCount", it fetches all the replies. I used breakpoints to see where it comes from since I didn't reference to it anywhere. It starts filling properties, assigns 3 to both, as one would expect. But after filling others properties, for some reason it jumps to setter and assigns 5 to RepliesCount. My theory; EF can fill the Replies if I want. Perhaps if I write the "Replies" then add "Count" at the end, it automatically runs the Count function and assigns to it? Because I didn't reference it anywhere.
58 replies