Gipper
Gipper
CC#
Created by Gipper on 7/22/2024 in #help
How to pass List<string> from one action to another using TempData
From what I saw on the internet I should do:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using Newtonsoft.Json;

public class MyController : Controller
{
public IActionResult FirstAction()
{
List<string> myList = new List<string> { "Item1", "Item2", "Item3" };
TempData["MyList"] = JsonConvert.SerializeObject(myList);

return RedirectToAction("SecondAction");
}

public IActionResult SecondAction()
{
List<string> myList = new List<string>();

if (TempData.ContainsKey("MyList"))
{
var myListJson = TempData["MyList"].ToString();
myList = JsonConvert.DeserializeObject<List<string>>(myListJson);
}

ViewBag.MyList = myList;
return View();
}
}
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using Newtonsoft.Json;

public class MyController : Controller
{
public IActionResult FirstAction()
{
List<string> myList = new List<string> { "Item1", "Item2", "Item3" };
TempData["MyList"] = JsonConvert.SerializeObject(myList);

return RedirectToAction("SecondAction");
}

public IActionResult SecondAction()
{
List<string> myList = new List<string>();

if (TempData.ContainsKey("MyList"))
{
var myListJson = TempData["MyList"].ToString();
myList = JsonConvert.DeserializeObject<List<string>>(myListJson);
}

ViewBag.MyList = myList;
return View();
}
}
But that seems wrong because whenever I try to do the line: var myListJson = TempData["MyList"].ToString(); I get a "cannot implicitly convert error". There should be a way to get back the list right, guys?
1 replies
CC#
Created by Gipper on 7/21/2024 in #help
How to go from taking in one photo upload to taking a multiple photo upload
Right now the way I'm doing it is:
public class MyViewModel
{
// some things
public IFormFile Photos { get; set; }
// etc...
}
public class MyViewModel
{
// some things
public IFormFile Photos { get; set; }
// etc...
}
and in the View I pass that ViewModel into I'm taking in the upload like this:
<form asp-action="MyAction" enctype="multipart/form-data">
Things before
<div class="custom-file">
<p for="customFile">Pick an image:</p>
<input asp-for="Photos" class="custom-file-input" id="customFile">
</div>
Things after
</form>
<form asp-action="MyAction" enctype="multipart/form-data">
Things before
<div class="custom-file">
<p for="customFile">Pick an image:</p>
<input asp-for="Photos" class="custom-file-input" id="customFile">
</div>
Things after
</form>
This only allows uploading one photo at a time. Stack Overflow tells me that the way to do multiple would be:
<asp:FileUpload ID="fileImages" AllowMultiple="true" runat="server" />
<asp:FileUpload ID="fileImages" AllowMultiple="true" runat="server" />
But since I didn't even know one can call asp classes in the html tag like that I would really appreciate some help and guidance on how to go from what I currently have to what I want to have.
75 replies
CC#
Created by Gipper on 7/21/2024 in #help
Not allowed to load local resource image error in browser console
Trying to load an image into a view with the path in the filesystem. I'm storing the images in the wwwroot folder. Is there a way around this error? I read I should set up a HTTP server on my computer but I have no idea how.
21 replies
CC#
Created by Gipper on 7/20/2024 in #help
How can I access the custom extra columns I tacked on to the AspNetUsers Identity db table?
I have an ASP.NET MVC app with a Users Model, but I am also using ASP.NET Identity. In order to avoid the confusion of the Identity built-in AspNetUsers table overlapping with my own Users table I simply inherited from Identity in my users model:
public partial class User : IdentityUser
{
public double userHeight {get;set;} // how tall user is
// other extra fields
}
public partial class User : IdentityUser
{
public double userHeight {get;set;} // how tall user is
// other extra fields
}
Which made EFCore simply append the "userHeight" column and other custom columns from the model on to the AspNetUsers table's already existing columns, which I was happy with. Problem being now I don't know how to access those extra columns. Here is how I access the current user entry in the AspNetUsers table, which I believe is how you're supposed to do it:
var currentUserTask = _userManager.GetUserAsync(User);
currentUserTask.Wait();
var currentUser = currentUserTask.Result;
var currentUserTask = _userManager.GetUserAsync(User);
currentUserTask.Wait();
var currentUser = currentUserTask.Result;
However the resulting currentUser variable will only hold the default Identity table columns and none of my extra ones I tacked on. I have tried to do it like so:
var utilizador = _context.Users.Find(currentUser.Id);
var utilizador = _context.Users.Find(currentUser.Id);
But that gives me an error "The instance of entity type 'User' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked." or something else about how the DbContext was already being accessed by another thread which never let go of the context (can't quite remember, something similar to that).
22 replies
CC#
Created by Gipper on 7/19/2024 in #help
How can I set bool to true in Model with radio input?
I may be doing this in an unconventional way as I am still learning, but I basically have this in my model
public class myModel
{
public myBool { get; set; } = false;
}
public class myModel
{
public myBool { get; set; } = false;
}
and I have a view based on that model that I would like to have a radio input tag that if checked will make myBool into true when the model object is submitted in the form. Something like:
<input type="radio" name="myBool" asp-for="myBool" value="true" />
<input type="radio" name="myBool" asp-for="myBool" value="true" />
It doesn't have to be done this way but I would prefer it in this way.
6 replies
CC#
Created by Gipper on 7/8/2024 in #help
How to create a foreign key pointing to the db table created by ASP.NET Identity (AspNetUsers)?
Hi! I'm making a house listings app for school, using the MVC pattern. Naturally, one of my main db tables is "HouseListings" and naturally one of the columns on that table is UserId and it's supposed to be based on a foreign key pointing to a user ID to associate that particular House Listing to the user that created it. What I wanted to do was avoid creating my own "Users" db table on top of the built in "AspNetUsers" one created automatically when I accepted the Identity schema, so I need to point to that in my HouseListings model class, but obviously AspNetUsers isn't in my Model. From my googling it seems that one can actually bring the Identity models explicitly into my project and work from there, but I don't think that would be necessary. Can I just do a dummy empty class in my Model? Like so:
public class User : IdentityUser
{
}
public class User : IdentityUser
{
}
Thus "bringing in" the AspNetUsers table into my Model and that way I can point to it in my "HouseListings" model class. Would this work? If not how can I make it work to do what I said?
20 replies
CC#
Created by Gipper on 7/7/2024 in #help
✅ Trouble setting up user-secrets
I'm trying to set up my ASP.NET app to send emails to confirm account registration. Following this documentation: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/accconfirm?view=aspnetcore-8.0&tabs=visual-studio Reffering to the section called "Configure SendGrid user secrets" when I try to input this command into my CLI:
dotnet user-secrets set sendGridKey MM$s85<Y60%X=q.BN+TN8z|Q%qQWie'|PxO
dotnet user-secrets set sendGridKey MM$s85<Y60%X=q.BN+TN8z|Q%qQWie'|PxO
I simply get another CLI prompt and not the success message shown in the documentation. What gives? HelP?
17 replies
CC#
Created by Gipper on 6/5/2024 in #help
Easiest and simplest way to insert a Microsoft SQL Server DB into an app saving data in csv files?
I got a solution with several projects, most of them are console applications, one is a gRPC server. I'm currently saving data in a sequence of csv files and I would like to do the same in a simple database with as many tables as I have csv files (about 6/7 of them). What would be the best way to inject a database in it? I say MSSQL Server only because that's the one I got setup on my system, could be another one hypothetically. So long as it's quick and easy 🙂
20 replies
CC#
Created by Gipper on 4/26/2024 in #help
Can I set up an integration testing environment with no app available and no code? If so, how?
Right now I have a test solution set up for ASP.NET and I can't launch it because it says WebServer failed to listen on port port_number. I am trying to use XUnit now:
public class TestesIntegracaoUser : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
private const string URLBase = "http://User";

public TestesIntegracaoUser(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
//Actual test code
}
public class TestesIntegracaoUser : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
private const string URLBase = "http://User";

public TestesIntegracaoUser(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
//Actual test code
}
I thought that WebApplicationFactory should have generated a web server for testing, but it's not doing so. I need it so I can debug this code, if I can.
78 replies
CC#
Created by Gipper on 4/24/2024 in #help
✅ Please help me read this simple API endpoint documentation
No description
51 replies
CC#
Created by Gipper on 4/16/2024 in #help
Help implementing multithreading in a distributed system, please?
I got a distributed system, meaning one solution that's a server and two which are clients. The objective is to use threads so that more than one client can communicate over TCP with the server simultaneously. I was told that I need to make it so there is some kind of code that makes it so different clients connect through different ports or the communication won't go well, but I really don't know. Any help you can give me? I know this isn't much to go on, but I'm trying to figure it out myself and feel free to ask questions and I'll do my best to answer.
53 replies
CC#
Created by Gipper on 4/10/2024 in #help
Help me sort out perhaps badly done folder/solution structure so I can add a shared Class Library
Ok, so I have two solutions which must be separate so I can execute them both at the same time so they will communicate (it includes TCP communication between them). They are both inside their own folder (called "Servidor" and "Cliente1") and both these folders are in turn inside a unifying folder called "TP1Code". Here's the output for the root folder of this project from the command line which may be enlightening (truncated for simplicity):
C:.
├───.vs
│ └───TP1
├───CommonLibrary
│ ├───bin
│ │ ├───Debug
│ │ │ └───net8.0
│ │ └───Release
│ │ └───net8.0
│ └───obj
│ ├───Debug
│ │ └───net8.0
│ │ ├───ref
│ │ └───refint
│ └───Release
│ └───net8.0
│ ├───ref
│ └───refint
└───TP1Code
├───.github
│ └───workflows
├───bin
│ ├───Debug
│ │ └───net8.0
│ └───Release
│ └───net8.0
├───Cliente1
│ ├───bin
│ │ ├───Debug
│ │ │ └───net8.0
│ │ └───Release
│ │ └───net8.0
│ └───obj
│ ├───Debug
│ │ └───net8.0
│ │ ├───ref
│ │ └───refint
│ └───Release
│ └───net8.0
│ ├───ref
│ └───refint
└───Servidor
├───bin
│ ├───Debug
│ │ └───net8.0
│ └───Release
│ └───net8.0
├───Files
├───obj
│ ├───Debug
│ │ └───net8.0
│ │ ├───ref
│ │ └───refint
│ └───Release
│ └───net8.0
│ ├───ref
│ └───refint
└───Properties
└───PublishProfiles
C:.
├───.vs
│ └───TP1
├───CommonLibrary
│ ├───bin
│ │ ├───Debug
│ │ │ └───net8.0
│ │ └───Release
│ │ └───net8.0
│ └───obj
│ ├───Debug
│ │ └───net8.0
│ │ ├───ref
│ │ └───refint
│ └───Release
│ └───net8.0
│ ├───ref
│ └───refint
└───TP1Code
├───.github
│ └───workflows
├───bin
│ ├───Debug
│ │ └───net8.0
│ └───Release
│ └───net8.0
├───Cliente1
│ ├───bin
│ │ ├───Debug
│ │ │ └───net8.0
│ │ └───Release
│ │ └───net8.0
│ └───obj
│ ├───Debug
│ │ └───net8.0
│ │ ├───ref
│ │ └───refint
│ └───Release
│ └───net8.0
│ ├───ref
│ └───refint
└───Servidor
├───bin
│ ├───Debug
│ │ └───net8.0
│ └───Release
│ └───net8.0
├───Files
├───obj
│ ├───Debug
│ │ └───net8.0
│ │ ├───ref
│ │ └───refint
│ └───Release
│ └───net8.0
│ ├───ref
│ └───refint
└───Properties
└───PublishProfiles
The important folders here are TP1Code itself, Servidor and Cliente1. What I want to do is add some code (only methods really) which is viewed and usable from within Servidor and Cliente1. Perhaps in the form of a Class Library?? Help?
60 replies
CC#
Created by Gipper on 4/3/2024 in #help
How to find relative file path for file inside of project?
Dealing with a C# console application, I have a folder inside the project named Files and inside that folder I have a file Servicos_A.csv. I want to get a relative path to that file for File I/O. My concern with using absolute path is that when I push it to github it won't work in my colleague's computer cause obviously his filesystem will be different from mine. How can I get to that path? I already searched it and asked generative AIs but it won't work, mostly because using the string assemblyDirectory = AppDomain.CurrentDomain.BaseDirectory utility for a part of the path seems to add some unnecessary and non-existing directories into the path for some reason.
2 replies
CC#
Created by Gipper on 3/5/2024 in #help
Advice on how to correctly integrate more complex Javascript code
Hey, I've developed an ASP.NET app before, but that one was pretty much all about the backend and the database. This next one I'm about to begin on will be almost the opposite, with much more complex frontend, particularly when it comes to Javascript code. Any advice on how to do it differently so to integrate everything properly and avoiding mistakes?
6 replies
CC#
Created by Gipper on 2/15/2024 in #help
Best way to do this OOP-wise???
Ok, so this is not the actual program but for the sake of brevity I'll give you an equivalent one:
namespace namespace1
{
internal class Program
{

static void Main(string[] args)
{
BaseClass baseClass = new BaseClass();
DerivedClass1 = new DerivedClass1();//Here I initialize fields in BaseClass
DerivedClass2 = new DerivedClass2();//Here I want the data initialized in BaseClass on the previous line
}
}
}
namespace namespace1
{
internal class Program
{

static void Main(string[] args)
{
BaseClass baseClass = new BaseClass();
DerivedClass1 = new DerivedClass1();//Here I initialize fields in BaseClass
DerivedClass2 = new DerivedClass2();//Here I want the data initialized in BaseClass on the previous line
}
}
}
internal class BaseClass
{
private protected int someData;
private protected string someMoreDataStr;
}
internal class BaseClass
{
private protected int someData;
private protected string someMoreDataStr;
}
internal class DerivedClass1 : BaseClass
{
\\THIS CLASS INITIALIZES DATA TO THE FIELDS IN BASECLASS
public DerivedClass1()
{
someData=3;
someMoreDataStr = "foo";
}
}
internal class DerivedClass1 : BaseClass
{
\\THIS CLASS INITIALIZES DATA TO THE FIELDS IN BASECLASS
public DerivedClass1()
{
someData=3;
someMoreDataStr = "foo";
}
}
internal class DerivedClass2 : BaseClass
{
\\This Class will be instantiated after DerivedClass1 And I want to have the 3 And the "foo" In there
public DerivedClass2()
{
\\I want to have the same data initialized earlier here
}
}
internal class DerivedClass2 : BaseClass
{
\\This Class will be instantiated after DerivedClass1 And I want to have the 3 And the "foo" In there
public DerivedClass2()
{
\\I want to have the same data initialized earlier here
}
}
Right now what I'm doing is:
namespace namespace1
{
internal class Program
{

static void Main(string[] args)
{
BaseClass baseClass = new BaseClass();
DerivedClass1 = new DerivedClass1(baseClass);//Here I initialize fields in BaseClass
DerivedClass2 = new DerivedClass2(baseClass);//Here I want the data initialized in BaseClass on the previous line
}
}
}
namespace namespace1
{
internal class Program
{

static void Main(string[] args)
{
BaseClass baseClass = new BaseClass();
DerivedClass1 = new DerivedClass1(baseClass);//Here I initialize fields in BaseClass
DerivedClass2 = new DerivedClass2(baseClass);//Here I want the data initialized in BaseClass on the previous line
}
}
}
and just accessing the data through the argument passed in to the constructor and I'm only inheriting so I can access the private protected field in BaseClass. Is there a better way of doing this (i.e. two classes derived from the same base sharing the values of the vars in the baseObj)? Should I just make the field public and not inherit?
24 replies
CC#
Created by Gipper on 1/31/2024 in #help
How to pass variable from one View to another View in link?
Ok, so I have this code in my view:
@foreach (var item in Model)
{
@if(Model.Any(utilizadorGrupo=>utilizadorGrupo.UtilizadorId == userID))
{
@if (userID == item.UtilizadorId)
{

<a id="nomeGrupo" href="@Url.Action("verPublicacaoGrupo")?nomeGrupo=@item.Grupo.Nome_grupo"><strong>@item.Grupo.Nome_grupo</strong></a>
}
}
}
@foreach (var item in Model)
{
@if(Model.Any(utilizadorGrupo=>utilizadorGrupo.UtilizadorId == userID))
{
@if (userID == item.UtilizadorId)
{

<a id="nomeGrupo" href="@Url.Action("verPublicacaoGrupo")?nomeGrupo=@item.Grupo.Nome_grupo"><strong>@item.Grupo.Nome_grupo</strong></a>
}
}
}
as you can see, in this view I am including a link to another view, I loop through a collection of objects and would like to pass the value of one of the fields of that object (Nome_grupo) to the view being linked to. I am doing it in the Razor syntax way because it seemed simpler, but I am open to any other way as this one has proved a bit wonky.
26 replies
CC#
Created by Gipper on 1/29/2024 in #help
How to use UserManager in my controller?
What the title says, what I'm doing currently:
private SignInManager<IdentityUser> _signInManager;
private UserManager<IdentityUser> _userManager;

public UtilizadoresController(ApplicationDbContext context, SignInManager<IdentityUser> signInManager, UserManager<IdentityUser> userManager)
{
_context = context;
_signInManager = signInManager;
_userManager = userManager;
}
private SignInManager<IdentityUser> _signInManager;
private UserManager<IdentityUser> _userManager;

public UtilizadoresController(ApplicationDbContext context, SignInManager<IdentityUser> signInManager, UserManager<IdentityUser> userManager)
{
_context = context;
_signInManager = signInManager;
_userManager = userManager;
}
But Visual Studio doesn't recognize the UserManager<IdentityUser> type: 'UserManager<>' is an ambiguous reference between 'Microsoft.AspNet.Identity.UserManager<TUser>' and 'Microsoft.AspNetCore.Identity.UserManager<TUser>' When I change it to private Microsoft.AspNet.Identity.UserManager<IdentityUser> _userManager; I get this error: 'Microsoft.AspNetCore.Identity.IdentityUser' cannot be used as type parameter 'TUser' in the generic type or method 'UserManager<TUser>'. There is no implicit reference conversion from 'Microsoft.AspNetCore.Identity.IdentityUser' to 'Microsoft.AspNet.Identity.IUser<string>'.
27 replies
CC#
Created by Gipper on 1/29/2024 in #help
How do I take text from input element of a form and put it in AspNetUsers table properly?
I'm passing it from view to controller action through parameters, if that's relevant. This input element has to have the attribute type="password" btw (it is a password) and I would like to be able to hash the text input in it like the system does and put it into AspNetUsers and also take what's already there and unhash it. I'm doing this cause I want to give the user a way to change their current password to a new one, if there is a better way I'm open to suggestions.
13 replies
CC#
Created by Gipper on 1/28/2024 in #help
✅ Changed something manually in AspNetUsers and now can't login
I went in with SQL Server Object Explorer and manually changed the NormalizedUserName column and now I can't login. I think that funked something up. What should I do?
22 replies
CC#
Created by Gipper on 1/22/2024 in #help
In an ASP.NET application, what is the way to in the view to check if user authenticated and roles?
I mean assuming you are using Asp.NET Identity resources and you have already scaffolded identity. Is it through HTTPContext? I know how to do it with [Authorize] in the controller, but that would require creating separate views for authenticated and non-authenticated viewers right? Is there an easier way through something like:
@if(check_if_authenticated)
{
//do stuff
}
@if(check_if_authenticated)
{
//do stuff
}
8 replies