C
C#2y ago
yumo

❔ SELECT MAX ID from textbox

Why is this displaying this error? System.FormatException: 'Incorrectly formatted input string.' This is my table sql
CREATE TABLE [dbo].[tbl_acoes] (
[acaoID] INT NOT NULL,
[data] NVARCHAR (MAX) NULL,
[local] NVARCHAR (MAX) NULL,
[indice] NVARCHAR (MAX) NULL,
[desc] NVARCHAR (MAX) NULL,
[foto] IMAGE NULL,
[estado] NVARCHAR (MAX) NULL,
[observacoes] NVARCHAR (MAX) NULL,
[validacao] NVARCHAR (MAX) NULL,
[ensaioID] INT NULL,
[idProjetos] INT NULL,
[descricaoacao] NVARCHAR (MAX) NULL,
[nensaio] INT NOT NULL,
PRIMARY KEY CLUSTERED ([acaoID] ASC),
CONSTRAINT [FK_tbl_acoes_tbl_ensaios] FOREIGN KEY ([ensaioID]) REFERENCES [dbo].[tbl_ensaios] ([ensaioID])
);
CREATE TABLE [dbo].[tbl_acoes] (
[acaoID] INT NOT NULL,
[data] NVARCHAR (MAX) NULL,
[local] NVARCHAR (MAX) NULL,
[indice] NVARCHAR (MAX) NULL,
[desc] NVARCHAR (MAX) NULL,
[foto] IMAGE NULL,
[estado] NVARCHAR (MAX) NULL,
[observacoes] NVARCHAR (MAX) NULL,
[validacao] NVARCHAR (MAX) NULL,
[ensaioID] INT NULL,
[idProjetos] INT NULL,
[descricaoacao] NVARCHAR (MAX) NULL,
[nensaio] INT NOT NULL,
PRIMARY KEY CLUSTERED ([acaoID] ASC),
CONSTRAINT [FK_tbl_acoes_tbl_ensaios] FOREIGN KEY ([ensaioID]) REFERENCES [dbo].[tbl_ensaios] ([ensaioID])
);
This is the code im using and what i want is select the max id of apples in the project number that is in the textbox
private void InserirIDEnsaios()
{
int novoID;
string query = "SELECT MAX(nensaio) FROM tbl_acoes WHERE idProjetos = '" + txtNIDPROJETOS.Text + "'";
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\infprog\\Desktop\\Patcher\\Oil\\bin\\Debug\\oil.mdf;Integrated Security=True");
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
novoID = int.Parse(cmd.ExecuteScalar().ToString()) + 1;
txtEnsaioID.Text = novoID.ToString();
}
con.Close();
}
}
private void InserirIDEnsaios()
{
int novoID;
string query = "SELECT MAX(nensaio) FROM tbl_acoes WHERE idProjetos = '" + txtNIDPROJETOS.Text + "'";
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\infprog\\Desktop\\Patcher\\Oil\\bin\\Debug\\oil.mdf;Integrated Security=True");
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
novoID = int.Parse(cmd.ExecuteScalar().ToString()) + 1;
txtEnsaioID.Text = novoID.ToString();
}
con.Close();
}
}
241 Replies
yumo
yumoOP2y ago
The number that will be in the blue box will be the number of the project that i select, thats done. But i want the greenbox to show the max id from that project in that textbox, what do i have wrong in my code?
Pobiega
Pobiega2y ago
Breaking some best practices here for sure, but to find what is causing that exact error, I suggest using breakpoints
yumo
yumoOP2y ago
Im going crazy with this, it seams easy to solve but im so tired of watching the same code over and over again
Pobiega
Pobiega2y ago
so, set a breakpoint at the top of your InserirIDEnsaios and run the debugger it should break, and you can now step line by line Im guessing its the new SqlConnection line thats doing it, but I'm not sure
yumo
yumoOP2y ago
The error is displaying in this line novoID = int.Parse(cmd.ExecuteScalar().ToString()) + 1; I thought it was because it had no data but i inserted some data and still displaying this
Pobiega
Pobiega2y ago
ah! well, its a bit weird that line you are using int.Parse, which WILL throw exceptions if the answer isnt an int and NOTHING BUT AN INT so maybe store the result, check what it is before parsing? var result = cmd.ExecuteScalar();
yumo
yumoOP2y ago
its saying that is 0 but it isnt
Tvde1
Tvde12y ago
at what line is it 0 make sure you are at least on the line after it's been set also, try to see what happens when you put a ' in your txtNIDPROJETOS text box :)
yumo
yumoOP2y ago
in the propertie text?
Tvde1
Tvde12y ago
In the textbox ye
yumo
yumoOP2y ago
Did nothing :/
Tvde1
Tvde12y ago
Just type it in the form
Pobiega
Pobiega2y ago
what do you mean, it did nothing
yumo
yumoOP2y ago
System.Data.SqlClient.SqlException: 'Unclosed quotation mark after the character string '''. Incorrect syntax near '''.'
Pobiega
Pobiega2y ago
if you put a breakpoint on that line and step through it
yumo
yumoOP2y ago
still the same
Pobiega
Pobiega2y ago
well read the code you are executing the command twice, which is a bit weird and you know its gonna crash on the int.Parse line
yumo
yumoOP2y ago
This is basicly incrementing +1 to the max id that is in the table
Pobiega
Pobiega2y ago
so you put the stuff I suggested to debug this AFTER the line that crashes
yumo
yumoOP2y ago
i normally use this because my teacher a few years ago he told me to do it like this What i want is basically read from the textbox, get the number that its in and see whats the max id from that number
Pobiega
Pobiega2y ago
I understand Now please break up that line that we know is crashing execute the command as its own step, with saving the scalar return value on its own THEN you can do the whole .tostring parse thing, if you want we just want it stored in its own variable so we can easily debug and see what the returned value is. understand?
yumo
yumoOP2y ago
Im a rookie in programming to be honest i have no clue what to do :/ I always had a default way to do things and now that isn't working because maybe its more complex im a lil scared ngl
yumo
yumoOP2y ago
9898 is the project name and the 2 is the number of essays in general. i changed the sql statment and i could open my app. But its still showing the max id of all essays and not atrributed to the textbox
yumo
yumoOP2y ago
string query = "select max(nensaio) from tbl_acoes where idProjetos like '" + txtNIDPROJETOS.Text + "%'"; this is what i changed to also tried this and still not working:
private void txtNIDPROJETOS_TextChanged(object sender, EventArgs e)
{
string query = "select max(nensaio) from tbl_acoes where idProjetos = '" + txtNIDPROJETOS.Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
txtEnsaioID.Text = reader["nensaio"].ToString();
}
con.Close();
}
private void txtNIDPROJETOS_TextChanged(object sender, EventArgs e)
{
string query = "select max(nensaio) from tbl_acoes where idProjetos = '" + txtNIDPROJETOS.Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
txtEnsaioID.Text = reader["nensaio"].ToString();
}
con.Close();
}
Pobiega
Pobiega2y ago
can we go back to the scalar for a sec? I don't think you actually tried what I suggested
yumo
yumoOP2y ago
yeah i said i didnt understand let me put the code how it was
Pobiega
Pobiega2y ago
Do you not understand basic variables? If you don't understand how to create and use variables, you should not be doing GUI and databases, to be honest
yumo
yumoOP2y ago
No, i was a front-end dev and im comming to make c# applications to get more understanding
Pobiega
Pobiega2y ago
okay
yumo
yumoOP2y ago
I think the best way to get in touch with these kind of stuff is throwing me to the wolves you know?
Pobiega
Pobiega2y ago
yes and no you need a solid foundation first then come the wolves
yumo
yumoOP2y ago
I really wanted to finish this at least, i know i need to understand more and more about it i need to make a research about online courses or something to guide me this is way more entertaining then front-end Could you help me finish this?
Pobiega
Pobiega2y ago
sure, but you'll need to actually listen and give it some effort
yumo
yumoOP2y ago
I will 100% Im motivated to learn and focus , thats why i was trying to make this on my own but stuck for a weak was making me crazy i see a huge gap on my knowledge about this 100%
Pobiega
Pobiega2y ago
okay so lets revert to the simplest version for now
var query = "select max(nensaio) from tbl_acoes where idProjetos = '" + txtNIDPROJETOS.Text + "'";
var cmd = new SqlCommand(query, con);
con.Open();
var result = cmd.ExecuteScalar();
con.Close();
var query = "select max(nensaio) from tbl_acoes where idProjetos = '" + txtNIDPROJETOS.Text + "'";
var cmd = new SqlCommand(query, con);
con.Open();
var result = cmd.ExecuteScalar();
con.Close();
if you put a breakpoint on the var result... line and step through it what value does result have? also, please note the return type on cmd.ExecuteScalar()
yumo
yumoOP2y ago
its returning null so its not getting any result right?
Pobiega
Pobiega2y ago
yep if you also check the calculated value of query, and run that in some database program (SSMS?) do you get a result?
yumo
yumoOP2y ago
1 sec
yumo
yumoOP2y ago
if i run the query like this:
select max(nensaio) from tbl_acoes where idProjetos = idProjetos;
select max(nensaio) from tbl_acoes where idProjetos = idProjetos;
its showing this
Pobiega
Pobiega2y ago
where idProjetos = idProjetos that doesnt really make sense? thats like saying where 1 = 1
yumo
yumoOP2y ago
isntead the last idProjetos i had the number of a project and that was saying NULL ofc because i didnt had anything to it
Pobiega
Pobiega2y ago
sure, if you had no rows at all you'd get no results aka a null result or actually, idk what MAX returns for an empty set.. null makes sense thou
yumo
yumoOP2y ago
yes but project number 668 i know that has nensaio registered and i was focusing on that one and it was showing the same error
Pobiega
Pobiega2y ago
okay so if you run select max(nensaio) from tbl_acoes where idProjetos = 668; in SSMS
yumo
yumoOP2y ago
shows NULL :/
yumo
yumoOP2y ago
but here you can see the last column
yumo
yumoOP2y ago
this one was added by hand this is my table tbl_acoes
Pobiega
Pobiega2y ago
uhm well looks to me like you have only one entry in that table and its not project id 668
yumo
yumoOP2y ago
my idProjetos is 3 that is equal to 668
Pobiega
Pobiega2y ago
but your query isn't for nprojeto you are doing where idProjetos = 668
yumo
yumoOP2y ago
yeah but the idProjetos is the primary key
Pobiega
Pobiega2y ago
yes?
yumo
yumoOP2y ago
its auto increment
Pobiega
Pobiega2y ago
so?
yumo
yumoOP2y ago
so if i talk about idProjetos wouldnt it search as nprojetos to?
Pobiega
Pobiega2y ago
.. no? why would it?
yumo
yumoOP2y ago
well because if i want to get information about the nprojeto 668 i can search it by idProjetos 3
Pobiega
Pobiega2y ago
sure OR just search by nprojeto
yumo
yumoOP2y ago
yes i guess its the same? so i should be searching for the nprojeto? and not the idProjeto wait so i was saying that the number 668 was in idProjetos
Pobiega
Pobiega2y ago
you should query the field that contains the value you actually want to search for...
yumo
yumoOP2y ago
and thats why was saying null?
Pobiega
Pobiega2y ago
also, legit question here why dont you name your tables, variables, methods etc in english?
yumo
yumoOP2y ago
Because im not english, but i will start doing that for sure
Pobiega
Pobiega2y ago
makes the code easier to read and understand for everyone
yumo
yumoOP2y ago
yeah ur right
Pobiega
Pobiega2y ago
I'm not english either, all my code is
yumo
yumoOP2y ago
but heres a thing
Pobiega
Pobiega2y ago
anyways I would highly suggest having your primary key just be Id
yumo
yumoOP2y ago
in my tbl_acoes i dont have the nprojeto in it , i have the idProjetos
Tvde1
Tvde12y ago
Do NOT fill in
'; DROP TABLE [dbo].[tbl_acoes]; --
'; DROP TABLE [dbo].[tbl_acoes]; --
Pobiega
Pobiega2y ago
we'll fix that later
Tvde1
Tvde12y ago
in your texbox
yumo
yumoOP2y ago
for every table?
Pobiega
Pobiega2y ago
yes they are always accessed as part of a table anyways SELECT Projects.Id, Projects.Name from Projects for example or
yumo
yumoOP2y ago
so the thing is wrong here is my sql statment
Pobiega
Pobiega2y ago
SELECT x.Id, x.Name, y.Id from Projects x, OtherTable y
yumo
yumoOP2y ago
right?
Pobiega
Pobiega2y ago
yes also, you are querying a number field, but giving a string as your search parameter and as far as I can tell, acaoID is actually your primary key
yumo
yumoOP2y ago
yeah from table tbl_acoes
Pobiega
Pobiega2y ago
thats the only table you have shown us
yumo
yumoOP2y ago
i always try to distinguish the primary keys of every table
Pobiega
Pobiega2y ago
and its the table you are querying Hm, I understand why you think thats a good idea but its not 😛
yumo
yumoOP2y ago
got it
Pobiega
Pobiega2y ago
not the problem here however lets fix your query for now, lets just skip the WHERE all tgether select max(nensaio) from tbl_acoes; if you run that in SSMS, do you get a hit?
yumo
yumoOP2y ago
one
yumo
yumoOP2y ago
idk why is it saying no column name tho
Pobiega
Pobiega2y ago
thats fine its expected even since you are not querying a column, you are querying the result from a function so, show me your C# code
yumo
yumoOP2y ago
private void InserirIDAcoes()
{
var query = "select max(nensaio) from tbl_acoes";
var cmd = new SqlCommand(query, con);
con.Open();
var result = cmd.ExecuteScalar();
con.Close();
}
private void InserirIDAcoes()
{
var query = "select max(nensaio) from tbl_acoes";
var cmd = new SqlCommand(query, con);
con.Open();
var result = cmd.ExecuteScalar();
con.Close();
}
Pobiega
Pobiega2y ago
great run that, with the breakpoint, inspect the value of result
yumo
yumoOP2y ago
well result still null :/
Pobiega
Pobiega2y ago
hm thats.. unexpected do you have a microphone and time to jump on a screen share?
yumo
yumoOP2y ago
in half an hour right now i have my kid sleeping right next to me it doesn't give me much comfort or either my wife will cut my throat 😅
Pobiega
Pobiega2y ago
Understandable.
yumo
yumoOP2y ago
If you can in 30 minutes we can hop on a call no problem about it I had a few problems at home can we talk maybe later or tomorrow? Sorry for the inconvenience Hi, sorry yesterday was kinda difficult for me to come to the pc so do you wanna have a look at this @Pobiega ? I stopped here:
private void InserirIDAcoes()
{
var query = "select max(nensaio) from tbl_acoes";
var cmd = new SqlCommand(query, con);
con.Open();
var result = cmd.ExecuteScalar();
con.Close();
}
private void InserirIDAcoes()
{
var query = "select max(nensaio) from tbl_acoes";
var cmd = new SqlCommand(query, con);
con.Open();
var result = cmd.ExecuteScalar();
con.Close();
}
so maybe i think i should work on the structure itself so give me one second i will do it all over again and in english so we can get a better view/idea well now i have a question, im givinf the same name id for each table but now i want to make a foreign key to it and this would be weird because this is my previous structure for table_essays
yumo
yumoOP2y ago
yumo
yumoOP2y ago
how am i gonna do this? this was why i was working with different names as PK's
Pobiega
Pobiega2y ago
erm, your FKs usually have names like... "TABLE1_TABLE2_FK" as in, the actual FK lets say a Project links to an Account in your Project, you'd have a AccountId and that is the Id column in the Accounts table
yumo
yumoOP2y ago
ok let me see if i can put this for me So basically i have Table_Projects and Table_Essays So Table_Essays get the id of the project so on Table_Essays i have to add a field called ProjectID right?
Pobiega
Pobiega2y ago
yes And regarding the names, dont prefix the tables like that Just call it Projects and Essays
yumo
yumoOP2y ago
got it i will change it real quick
Pobiega
Pobiega2y ago
👍
yumo
yumoOP2y ago
so now to create FK's its in relationships right?
Pobiega
Pobiega2y ago
Was a long time since I set tables up manually, but yeah sounds reasonable 🙂
yumo
yumoOP2y ago
so like this the PK is from Projects and the FK is on Essays table
yumo
yumoOP2y ago
i think i will do it in SQL idk why isnt working 🥲
Pobiega
Pobiega2y ago
no idea 😛 I'll start my ssms and try
yumo
yumoOP2y ago
ALTER TABLE Essays
ADD CONSTRAINT fk_essay_id
FOREIGN KEY (projectId)
REFERENCES Projects(id)
ALTER TABLE Essays
ADD CONSTRAINT fk_essay_id
FOREIGN KEY (projectId)
REFERENCES Projects(id)
either way i did it like this
Pobiega
Pobiega2y ago
sounds about right
yumo
yumoOP2y ago
well now i think its the most confusing part of it I have 3 Tables: Projects Essays Actions a project must contain essays, but the essays may and may not have actions
Pobiega
Pobiega2y ago
Sure
yumo
yumoOP2y ago
so i need to add a FK on Actions of the id in the Essays
Pobiega
Pobiega2y ago
yep
yumo
yumoOP2y ago
well idk why if i place another int data type in my table it doesnt let me save it well i see its not the data type
yumo
yumoOP2y ago
but have no clue why this is showing
Pobiega
Pobiega2y ago
¯\_(ツ)_/¯
yumo
yumoOP2y ago
it accepts it only as nchar o.O
Pobiega
Pobiega2y ago
As said, I don't really use the designer at all I almost exclusively use Entity framework with code first, and thus migrations
yumo
yumoOP2y ago
u even create the table as SQL command ?
Pobiega
Pobiega2y ago
no, thats all done via migrations But this is fine for now, as long as you can get it working 🙂 but yeah Im having the same issues with SSMS, any adding of a new column when FKs are present gives that error very weird but adding stuff via ALTER TABLE [x] ADD [y] ... works fine
yumo
yumoOP2y ago
yeah
ALTER TABLE Aactions
ADD CONSTRAINT fk_action_id
FOREIGN KEY (essayId)
REFERENCES Essays(id)
ALTER TABLE Aactions
ADD CONSTRAINT fk_action_id
FOREIGN KEY (essayId)
REFERENCES Essays(id)
this is what i did for table Aactions but now i have a question
Pobiega
Pobiega2y ago
sure
yumo
yumoOP2y ago
Aactions can and cannot have Essays associated, how can i make it if doesnt have an Essay, stays associated with the Project? Is that on code and the SQL structure is fine or do i need to have a FK from Aactions to Projects?
Pobiega
Pobiega2y ago
So an action is always associated with a project, but the essay link is optional?
yumo
yumoOP2y ago
the opposite the essay is always associated
Pobiega
Pobiega2y ago
but you said essays are optional
yumo
yumoOP2y ago
and the action can associate with Essay or Project i mean actions sorry
Pobiega
Pobiega2y ago
?
yumo
yumoOP2y ago
actions are optional not the essays
Pobiega
Pobiega2y ago
well if they are optional, doesnt that just mean they dont exist? like, you can have a project with one or more essays and not a single action thats fine, and your design already supports that
yumo
yumoOP2y ago
well good then
Pobiega
Pobiega2y ago
remember, relationships are kind of inverted in SQL a project doesnt "own" essays, essays instead indicate what project they belong to
yumo
yumoOP2y ago
yes im gonna make the design of the page real quick something simple
Pobiega
Pobiega2y ago
How about we focus on getting to the point where you can actually query the database from C# first? 🙂
yumo
yumoOP2y ago
oh yeah databinding it right?
Pobiega
Pobiega2y ago
no, please no.
yumo
yumoOP2y ago
using server explorer?
Pobiega
Pobiega2y ago
no
yumo
yumoOP2y ago
how then 🤔
Pobiega
Pobiega2y ago
something like this
public class Program
{
public static void Main()
{
var conn = new SqlConnection("Data Source=.;Initial Catalog=Experiments;User Id=sa;Password=aaaAAA!!!");

var query = "SELECT COUNT(*) FROM Actions;";

using var cmd = new SqlCommand(query, conn);
conn.Open();
var result = cmd.ExecuteScalar();

if (result != null)
{
Console.WriteLine($"Result was: {result}");
}

conn.Close();
}
}
public class Program
{
public static void Main()
{
var conn = new SqlConnection("Data Source=.;Initial Catalog=Experiments;User Id=sa;Password=aaaAAA!!!");

var query = "SELECT COUNT(*) FROM Actions;";

using var cmd = new SqlCommand(query, conn);
conn.Open();
var result = cmd.ExecuteScalar();

if (result != null)
{
Console.WriteLine($"Result was: {result}");
}

conn.Close();
}
}
this is a console app that just queries my local database its as simple as can possibly be, but it works
yumo
yumoOP2y ago
Oh yeah, i forgot to tell you so im doing the CRUD all over again, since i turned everything and in English , that's why i was saying i was designing the page
Pobiega
Pobiega2y ago
sure, but that can wait lets get the actual query working
yumo
yumoOP2y ago
oh okok so i need to create that class
Pobiega
Pobiega2y ago
because yesterday, you kept getting null regardless of what you put in your query this isnt a winforms app thou, its actually a console app just to get the smallest possible test
yumo
yumoOP2y ago
ohhh i cant use the resource using because this is C#7.3 and i need to use the version 8.0 or higher
Pobiega
Pobiega2y ago
why are you using a really old version of .NET? if you are limited to 7.3 Im guessing you are using .NET Framework, probably 4.7 or 4.8
yumo
yumoOP2y ago
well im not limited i can change to the most updated one
Pobiega
Pobiega2y ago
I would encourage you to do so .net framework is legacy and only getting security fixes at this point while .NET (currently at version 7) is the future and getting new content
yumo
yumoOP2y ago
How can i update it here in visual studio 2022? never done that
Pobiega
Pobiega2y ago
if you have VS 2022, you might already have it
Pobiega
Pobiega2y ago
Pobiega
Pobiega2y ago
the top one is the modern version, the bottom one is old and legacy this goes for winforms too
yumo
yumoOP2y ago
yumo
yumoOP2y ago
the other option is .NET 7.0
Pobiega
Pobiega2y ago
go for 7 🙂
yumo
yumoOP2y ago
do i check the checkbox?
Pobiega
Pobiega2y ago
6 is long term support, 7 is short term (8 comes in november and will be the new LTS) hang on, I dont speak portuguese
yumo
yumoOP2y ago
oh sorry dont use instruction of higher level
Pobiega
Pobiega2y ago
"dont use top level statements" 😄 ah proibably best to check it for now .NET recently introduced the ability to skip the boilerplate in the main class, and its nice but often confuses people at first
yumo
yumoOP2y ago
yumo
yumoOP2y ago
all good 4 now
Pobiega
Pobiega2y ago
great! now, just change the connection string
yumo
yumoOP2y ago
well yeah i need to add the SqlConnection because its not getting recognized
Pobiega
Pobiega2y ago
right, you need to add the NuGet System.Data.SqlClient
yumo
yumoOP2y ago
wow winforms does all this automatically
Pobiega
Pobiega2y ago
not really winforms also needs to add the sql client, Im pretty sure
yumo
yumoOP2y ago
if you have SqlConnection or so it adds the System.Data.SqlClient; either way its done i will get the connection string
Pobiega
Pobiega2y ago
it will do that here too, once you have installed the package
yumo
yumoOP2y ago
how can i get the conenction string in SSMS?
Pobiega
Pobiega2y ago
if you rightclick on "dependencies" in the solution explorer, you should see "manage nuget packages" thats where you can install it I have no idea 🙂
yumo
yumoOP2y ago
got it i've seen connection strings like this
var conn = new SqlConnection(@"Data Source=(LOCALDB)\\MSSQLLocalDB;Initial Catalog=ssms;Integrated Security=True");
var conn = new SqlConnection(@"Data Source=(LOCALDB)\\MSSQLLocalDB;Initial Catalog=ssms;Integrated Security=True");
whats the difference of the @ behind the double quotes?
Pobiega
Pobiega2y ago
it means "verbatim string" it escapes stuff
yumo
yumoOP2y ago
oh ok
Pobiega
Pobiega2y ago
or rather, it doesnt so "\n" and @"\n" dont mean the same thing the first means "newline"; the second literally means "backslash-n"
yumo
yumoOP2y ago
okok got it connection string done
Pobiega
Pobiega2y ago
okay give it a spin I have a single row in my actions, so I get 1 as my result
yumo
yumoOP2y ago
Result as 0
Pobiega
Pobiega2y ago
thats good, means the query succesfully ran at least assuming you do indeed have an empty actions table 🙂
yumo
yumoOP2y ago
yes i have ^^
Pobiega
Pobiega2y ago
great! that means you can now start working on the winforms app 🙂
Pobiega
Pobiega2y ago
yumo
yumoOP2y ago
that's what i use yeah one question before i start
Pobiega
Pobiega2y ago
you sure its the .net 7 winforms you are using? 🙂
yumo
yumoOP2y ago
should i make the login system now or i can do it later? i would love to make some sort of login system that saves the user data
Pobiega
Pobiega2y ago
If you want a login system, you should do a login system
yumo
yumoOP2y ago
Pobiega
Pobiega2y ago
you picked the other one when you made the project
yumo
yumoOP2y ago
so i go for 4.8?
Pobiega
Pobiega2y ago
no, you create a new project and select the non-framework project 🙂
yumo
yumoOP2y ago
ohhhhhhhhhhhhhh i see .NET 7.0
Pobiega
Pobiega2y ago
yup!
yumo
yumoOP2y ago
right? in the other project i was working with the .net framework so should i make it now ?
Pobiega
Pobiega2y ago
why not if you want one, now is a good time to make it because I think future systems might need to integrate with it
yumo
yumoOP2y ago
kinda nervous about it 😅
Pobiega
Pobiega2y ago
like..
When adding a new [something] to the database, also write down who added it. Get data from current logged in user.
yumo
yumoOP2y ago
i've been following some tutorials on the internet but its a little bit confusing yeah that would be cool so first of all i need to make the users table well table users done wow this is way different i cannot double click the button and give the code for it do i need to say it as event?
Pobiega
Pobiega2y ago
uhm, you should be able to
yumo
yumoOP2y ago
it goes for the MainMenu_Load when i double click
Pobiega
Pobiega2y ago
works for me
yumo
yumoOP2y ago
weird
Pobiega
Pobiega2y ago
I dragged out a button, double clicked it, got an OnClick event
yumo
yumoOP2y ago
gonna restart the visual studio
Pobiega
Pobiega2y ago
👍
yumo
yumoOP2y ago
now im getting the event
Pobiega
Pobiega2y ago
I'd like to recommend a few things to you btw first is Dapper its a way to easily bind your SQL query results to objects in C#, makes it SOOOOO much easier to work with SQL
yumo
yumoOP2y ago
i've heard that before but never used it
Pobiega
Pobiega2y ago
You'll also need to think carefully about how you structure your app, you dont want to be writing your database code inside the Clicked event directly it would be a lot better to instead just have the button issue a command of some sort to a "different part" of the application and let it handle the actual work
yumo
yumoOP2y ago
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source";
con.Open();
string userid = txtUtilizador.Text;
string password = txtSenha.Text;
SqlCommand cmd = new SqlCommand("select utilizador,password from tbl_login where utilizador='" + txtUtilizador.Text + "'and password='" + txtSenha.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
this.Hide();
MessageBox.Show("sucess!");
MenuPrincipal sistema = new MenuPrincipal();
sistema.ShowDialog();
}
else
{
MessageBox.Show("Utilizador or password invalid");
}
con.Close();
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source";
con.Open();
string userid = txtUtilizador.Text;
string password = txtSenha.Text;
SqlCommand cmd = new SqlCommand("select utilizador,password from tbl_login where utilizador='" + txtUtilizador.Text + "'and password='" + txtSenha.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
this.Hide();
MessageBox.Show("sucess!");
MenuPrincipal sistema = new MenuPrincipal();
sistema.ShowDialog();
}
else
{
MessageBox.Show("Utilizador or password invalid");
}
con.Close();
is this good?
Pobiega
Pobiega2y ago
Not really 🙂
yumo
yumoOP2y ago
🥲
Pobiega
Pobiega2y ago
its mixing database code with logic and presentation so you are mixing three things that should not be mixed
yumo
yumoOP2y ago
wow i've been doing this for a while now 😅
Pobiega
Pobiega2y ago
haha thats fine, we all did when we first learned but the code quickly gets messy, and you might end up duplicating a lot of logic
yumo
yumoOP2y ago
yeah if i show u my last project u would cry 🥲 500 lines or so the majority being sql connections xD doing this my whole life and now seeing the dumb things this creates jeez so how would you do this button ? or whats the proper way to do it
Pobiega
Pobiega2y ago
oh boy
yumo
yumoOP2y ago
oh thats a nono 🤣
Pobiega
Pobiega2y ago
first, I would use a "Unit of work" pattern to ensure transactional security I would likely use EF, but since you are not, I'd use dapper and write repos around it
yumo
yumoOP2y ago
this one right?
Pobiega
Pobiega2y ago
yes
yumo
yumoOP2y ago
i installed the nuget allready should i create a class to make my functions there?
Pobiega
Pobiega2y ago
yes
yumo
yumoOP2y ago
i was trying to search anything online or a video i could follow to do this but im lost
Pobiega
Pobiega2y ago
public class UserService
{
private readonly UserRepository _userRepository;
private readonly AppSettings _settings;

public UserService(UserRepository userRepository, AppSettings settings)
{
_userRepository = userRepository;
_settings = settings;
}

public User? LoginUser(string username, string password)
{
var hash = BcryptHelper.Hash(password, _settings.UserPasswordSalt);

var dbUser = _userRepository.GetUser(username, hash);

if (dbUser == null)
{
return null;
}
return User.FromDbUser(dbUser);
}
}

public class UserRepository
{
private readonly SqlConnection _connection;

public UserRepository(SqlConnection connection)
{
_connection = connection;
}

public DbUser? GetUser(string username, string passwordHash)
{
var param = new { Username = username, PasswordHash = passwordHash };
var result = _connection.Query<DbUser>("SELECT Username FROM [Users] WHERE [Username] = @Username AND [PasswordHash] = @PasswordHash", param)?.ToList();

return result?.SingleOrDefault();
}
}
public class UserService
{
private readonly UserRepository _userRepository;
private readonly AppSettings _settings;

public UserService(UserRepository userRepository, AppSettings settings)
{
_userRepository = userRepository;
_settings = settings;
}

public User? LoginUser(string username, string password)
{
var hash = BcryptHelper.Hash(password, _settings.UserPasswordSalt);

var dbUser = _userRepository.GetUser(username, hash);

if (dbUser == null)
{
return null;
}
return User.FromDbUser(dbUser);
}
}

public class UserRepository
{
private readonly SqlConnection _connection;

public UserRepository(SqlConnection connection)
{
_connection = connection;
}

public DbUser? GetUser(string username, string passwordHash)
{
var param = new { Username = username, PasswordHash = passwordHash };
var result = _connection.Query<DbUser>("SELECT Username FROM [Users] WHERE [Username] = @Username AND [PasswordHash] = @PasswordHash", param)?.ToList();

return result?.SingleOrDefault();
}
}
something like this
yumo
yumoOP2y ago
all i get is for websites :/
Pobiega
Pobiega2y ago
note that the code above is mostly for demonstration, I just whipped it up right now
yumo
yumoOP2y ago
yeah i saw that its missing some asseblys, for the login system i need Syte.Data.SqlClietn; But i need sum more
Pobiega
Pobiega2y ago
well, this code assumes...
using System.Data.SqlClient;
using Dapper;
using System.Data.SqlClient;
using Dapper;
thats it I created the rest myself
yumo
yumoOP2y ago
how do i use dapper then im fully confused
Pobiega
Pobiega2y ago
var param = new { Username = username, PasswordHash = passwordHash };
var result = _connection.Query<DbUser>("SELECT Username FROM [Users] WHERE [Username] = @Username AND [PasswordHash] = @PasswordHash", param)?.ToList();
var param = new { Username = username, PasswordHash = passwordHash };
var result = _connection.Query<DbUser>("SELECT Username FROM [Users] WHERE [Username] = @Username AND [PasswordHash] = @PasswordHash", param)?.ToList();
thats using dapper the .Query<T> method is from dapper
yumo
yumoOP2y ago
yeah but its stil displaying as an error
Pobiega
Pobiega2y ago
well you don't have a DbUser class
yumo
yumoOP2y ago
this is a new world for me ngl I was used to one thing and now it's all very complicated
Pobiega
Pobiega2y ago
You know what a class is thou, right?
yumo
yumoOP2y ago
yeah but the thing is i've never coded like this before
Pobiega
Pobiega2y ago
So the idea of mapping the response from a database query to an object (an instance of a class) shouldt be that weird
yumo
yumoOP2y ago
idk maybe im just confused, tired , idk i slept 3 hours
Pobiega
Pobiega2y ago
Well, to be fair, it is quite the step up from "just write the code that does the thing" to planning and separating out your code but it makes for better code
yumo
yumoOP2y ago
true
Pobiega
Pobiega2y ago
Do you have time for a screenshare call? I could show you the ideas and how I go about doing stuff like this
yumo
yumoOP2y ago
i think im gonna rest a lil bit and we can have a look afterwards not feeling quite good
Pobiega
Pobiega2y ago
I leave no guarantees that I have time later 😛
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server